typescript/prefer-includes Pedantic
它的作用
🌐 What it does
强制使用 .includes() 而不是 .indexOf() !== -1 或 /regex/.test()。
🌐 Enforce using .includes() instead of .indexOf() !== -1 or /regex/.test().
这为什么不好?
🌐 Why is this bad?
.includes() 比检查 .indexOf() !== -1 更易读且更具表达力。它清楚地传达了检查值是否存在的意图。此外,对于简单的字符串搜索,.includes() 通常优于正则表达式 .test(),以获得更好的性能和更清晰的代码。
例子
🌐 Examples
此规则的 错误 代码示例:
🌐 Examples of incorrect code for this rule:
ts
// Using 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");
}
// Using regex test for simple strings
if (/world/.test(str)) {
console.log("found");
}
// Arrays
const arr = [1, 2, 3];
if (arr.indexOf(2) !== -1) {
console.log("found");
}此规则的正确代码示例:
🌐 Examples of correct code for this rule:
ts
// Using includes for strings
const str = "hello world";
if (str.includes("world")) {
console.log("found");
}
// Using includes for arrays
const arr = [1, 2, 3];
if (arr.includes(2)) {
console.log("found");
}
// Complex regex patterns are allowed
if (/wo+rld/.test(str)) {
console.log("found");
}
// Regex with flags
if (/world/i.test(str)) {
console.log("found");
}如何使用
🌐 How to use
要通过配置文件或命令行启用此规则,你可以使用:
🌐 To enable this rule using the config file or in the CLI, you can use:
json
{
"rules": {
"typescript/prefer-includes": "error"
}
}bash
oxlint --type-aware --deny typescript/prefer-includes参考文献
🌐 References
