typescript/prefer-includes Pedantic
功能说明
强制使用 .includes() 而不是 .indexOf() !== -1 或 /regex/.test()。
为什么这样做是不好的?
.includes() 比检查 .indexOf() !== -1 更具可读性和表达力。它清楚地传达了检查值是否存在的意图。此外,对于简单的字符串搜索,.includes() 通常比正则表达式 .test() 更受青睐,因为性能更好且更清晰。
示例
此规则的错误代码示例:
ts
// 使用 indexOf
const str = "hello world";
if (str.indexOf("world") !== -1) {
console.log("found");
}
if (str.indexOf("world") != -1) {
console.log("found");
}
if (str.indexOf("world") > -1) {
console.log("found");
}
// 对简单字符串使用正则表达式 test
if (/world/.test(str)) {
console.log("found");
}
// 数组
const arr = [1, 2, 3];
if (arr.indexOf(2) !== -1) {
console.log("found");
}此规则的正确代码示例:
ts
// 对字符串使用 includes
const str = "hello world";
if (str.includes("world")) {
console.log("found");
}
// 对数组使用 includes
const arr = [1, 2, 3];
if (arr.includes(2)) {
console.log("found");
}
// 允许使用复杂正则表达式模式
if (/wo+rld/.test(str)) {
console.log("found");
}
// 带标志的正则表达式
if (/world/i.test(str)) {
console.log("found");
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/prefer-includes": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/prefer-includes": "error",
},
});bash
oxlint --type-aware --deny typescript/prefer-includes版本
此规则在 v1.29.0 中添加。