typescript/prefer-includes 严格
它做了什么
强制使用 .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");
}
// 对简单字符串使用 regex 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");
}如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/prefer-includes": "error"
}
}bash
oxlint --type-aware --deny typescript/prefer-includes