typescript/prefer-find Style
它的作用
优先使用 .find(...) 而不是 .filter(...)[0] 来获取单个元素。
这为什么不好?
.filter(...)[0] 会构建一个中间数组,而且不能清晰地表达意图。 .find(...) 直接表达只需要第一个匹配元素。
示例
以下是此规则的错误代码示例:
ts
const first = list.filter((item) => item.active)[0];以下是此规则的正确代码示例:
ts
const first = list.find((item) => item.active);如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/prefer-find": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/prefer-find": "error",
},
});bash
oxlint --type-aware --deny typescript/prefer-find版本
此规则于 v1.49.0 中添加。
