@typescript-eslint/prefer-find

Require .find() instead of .filter()[0] to get the first match

has suggestionsneeds types

Also called typescript-eslint/prefer-find, typescript/prefer-find

.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#

example.ts2 problems
declare const users: { name: string; admin: boolean }[];

const admin = users.filter(user => user.admin)[0];
const guest = users.filter(user => !user.admin).at(0);
example.tsNo problems
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:

example.tsNo problems
class Query {
  filter(condition: string): string[] {
    return [condition];
  }
}

const row = new Query().filter("active = 1")[0];