Skip to content

arrayIncludes

Reports using .indexOf() comparisons that can be replaced with .includes().

✅ This rule is included in the ts stylistic presets.

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. ES2015 added String.prototype.includes() and ES2016 added Array.prototype.includes(), which are more readable and expressive.

This rule reports when an .indexOf() comparison can be replaced with .includes(). It checks for any receiver object that has both .indexOf() and .includes() methods with compatible parameters.

Matching types include: String, Array, ReadonlyArray, and typed arrays.

declare const array: number[];
declare const value: number;
array.indexOf(value) !== -1;
declare const array: number[];
declare const value: number;
array.indexOf(value) === -1;
declare const array: number[];
declare const value: number;
array.indexOf(value) > -1;
declare const array: number[];
declare const value: number;
array.indexOf(value) >= 0;
declare const str: string;
str.indexOf("test") !== -1;

This rule is not configurable.

If you need to support environments that don’t have Array.prototype.includes() (pre-ES2016) or String.prototype.includes() (pre-ES2015), or if you need the actual index returned by .indexOf(), you may disable this rule.

Made with ❤️‍🔥 in Boston by Josh Goldberg and contributors.