Linter · Rules
@typescript-eslint/prefer-find
Require .find() instead of .filter()[0] to get the first match
.filter(...)[0] tests every element and builds a new array, then uses only its first element. .find(...) stops at the first match and returns it.
.filter(...).at(0) is reported too. Only arrays and tuples are checked.
Configure
Off by default. This rule needs types, so turning it on makes bun lint type check your code first.
bunfig.toml
[lint.rules]
"@typescript-eslint/prefer-find" = "error" # or "warn"
Examples
Reported:
declare const users: { name: string; admin: boolean }[];
const admin = users.filter(user => user.admin)[0];
const guest = users.filter(user => !user.admin).at(0);
Not reported:
declare const users: { name: string; admin: boolean }[];
const admin = users.find(user => user.admin);
const second = users.filter(user => user.admin)[1];
A filter method on your own class is left alone:
class Query {
filter(condition: string): string[] {
return [condition];
}
}
const row = new Query().filter("active = 1")[0];