Skip to main content

prefer-includes

Enforce includes method over indexOf method.

🔧

Some problems reported by this rule are automatically fixable by the --fix ESLint command line option.

💭

This rule requires type information to run.

Prior to ES2015, Array#indexOf and String#indexOf comparisons against -1 were the standard ways to check whether a value exists in an array or string, respectively. Alternatives that are easier to read and write now exist: ES2015 added String#includes and ES2016 added Array#includes.

This rule reports when an .indexOf call can be replaced with an .includes. Additionally, this rule reports the tests of simple regular expressions in favor of String#includes.

This rule will report on any receiver object of an indexOf method call that has an includes method where the two methods have the same parameters. Matching types include: String, Array, ReadonlyArray, and typed arrays.

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-includes": "error"
}
};

Try this rule in the playground ↗

Examples

const str: string;
const array: any[];
const readonlyArray: ReadonlyArray<any>;
const typedArray: UInt8Array;
const maybe: string;
const userDefined: {
indexOf(x: any): number;
includes(x: any): boolean;
};

str.indexOf(value) !== -1;
array.indexOf(value) !== -1;
readonlyArray.indexOf(value) === -1;
typedArray.indexOf(value) > -1;
maybe?.indexOf('') !== -1;
userDefined.indexOf(value) >= 0;

/example/.test(str);
Open in Playground

Options

This rule is not configurable.

When Not To Use It

Type checked lint rules are more powerful than traditional lint rules, but also require configuring type checked linting.

See Troubleshooting > Linting with Type Information > Performance if you experience performance degredations after enabling type checked rules.

Resources