Skip to main content

prefer-includes

Enforce includes method over indexOf method.

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

💭

该规则需要 类型信息 才能运行,但这会带来性能方面的权衡。

在 ES2015 之前,Array#indexOfString#indexOf-1 的比较是分别检查值是否存在于数组或字符串中的标准方法。现在存在更易于阅读和编写的替代方案:ES2015 添加了 String#includes,ES2016 添加了 Array#includes

¥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.

此规则报告何时可以用 .includes 替换具有显式文字类型的 .indexOf。此外,此规则报告了支持 String#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.

此规则将报告具有 includes 方法的任何 indexOf 方法调用的接收者对象,其中两个方法具有相同的参数。匹配类型包括:StringArrayReadonlyArray 和类型化数组。

¥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.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/prefer-includes": "error"
}
});

在线运行试试这个规则 ↗

示例

¥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

选项

该规则不可配置。

何时不使用它

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 degradations after enabling type checked rules.

'## 资源'