Skip to main content

prefer-includes

Enforce includes method over indexOf method.

🔒

Extending "plugin:@typescript-eslint/strict" in an ESLint configuration enables this rule.

🛠

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": "warn"
}
};

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);

Options

This rule is not configurable.

When Not To Use It

If you don't want to suggest includes, you can safely turn this rule off.

Resources