I saw a silly bug in my code, which I think a linter could have prevented.
I currently use this ESLint (v9) config for TypeScript:
// @ts-check
import eslint from '@eslint/js';
import tseslint from 'typescript-eslint';
export default tseslint.config(
eslint.configs.recommended,
tseslint.configs.recommended,
{
rules: {
"@typescript-eslint/no-explicit-any": "warn"
}
}
);
This code sample shows the issue which the linter didn't identify:
const str: string = "1234";
let hasZero = str.indexOf("0") ? "yes" : "no";
console.log(hasZero);
console.log(`hasZero is '${hasZero}'!`);
This TypeScript code always returns "yes" in this sample.
Someone else proposed to use the "@typescript-eslint/prefer-includes": "error"
rule, but it returns all OK in the online ESLint playground site.
I know the solution for the code error (str.indexOf("0") > -1
or even better str.includes("0")
), but I want to get the linter warn me when I make such a lazy mistake again.
So, what rule would detect this bad code practice?