typescript/prefer-string-starts-ends-with Style
它的作用
优先使用 startsWith 和 endsWith,而不是手动进行字符串边界检查。
为什么这不好?
使用 slice、indexOf、正则锚点或手动索引编写的边界检查, 比 startsWith/endsWith 更难阅读和维护。
示例
以下是此规则的错误代码示例:
ts
value.slice(0, 3) === "foo";
value.slice(-3) === "bar";以下是此规则的正确代码示例:
ts
value.startsWith("foo");
value.endsWith("bar");配置
此规则接受一个包含以下属性的配置对象:
allowSingleElementEquality
type: "always" | "never"
default: "never"
是否允许对第一个/最后一个字符进行相等性检查。
"always"
始终允许对第一个或最后一个字符进行相等性检查。
"never"
从不允许对第一个或最后一个字符进行相等性检查。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/prefer-string-starts-ends-with": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/prefer-string-starts-ends-with": "error",
},
});bash
oxlint --type-aware --deny typescript/prefer-string-starts-ends-with版本
此规则是在 v0.0.8 中添加的。
