Skip to main content

prefer-includes

Enforce includes method over indexOf method.

🔒

ESLint 配置 中扩展"plugin:@typescript-eslint/strict-type-checked" 可启用此规则。

🔧

此规则报告的一些问题可通过 --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.

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

.eslintrc.cjs
module.exports = {
"rules": {
"@typescript-eslint/prefer-includes": "error"
}
};
在线运行试试这个规则 ↗

示例

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

选项

该规则不可配置。

资源