Rules Hub
Coding Rules Library
Prefer inferred type predicates in filter
Avoid defining manual type predicates in array filter callbacks when TypeScript can infer narrowing automatically.
Bad example
| 1 | const signals: (AbortSignal | null)[] = [new AbortController().signal, null]; |
| 2 |
|
| 3 | // Redundant manual type predicate |
| 4 | const active = signals.filter((s): s is AbortSignal => { |
| 5 | return s instanceof AbortSignal; |
| 6 | }); |
Explanation (EN)
Manually defining the type predicate (`: s is Type`) is verbose and redundant in modern TypeScript. It also creates a maintenance burden, as the type definition must be manually synced with the implementation logic.
Objašnjenje (HR)
Ručno definiranje predikata tipa (`: s is Type`) je opširno i suvišno u modernom TypeScriptu. Također stvara teret održavanja jer se definicija tipa mora ručno usklađivati s implementacijskom logikom.
Good example
| 1 | const signals: (AbortSignal | null)[] = [new AbortController().signal, null]; |
| 2 |
|
| 3 | // TypeScript 5.5+ automatically infers the type predicate |
| 4 | const active = signals.filter((s) => { |
| 5 | return s instanceof AbortSignal; |
| 6 | }); |
Explanation (EN)
TypeScript automatically infers that the array is narrowed based on the return statement. This reduces visual noise and ensures the type narrowing is always truthful to the runtime check.
Objašnjenje (HR)
TypeScript automatski zaključuje da je niz sužen na temelju `return` izraza. To smanjuje vizualni šum i osigurava da sužavanje tipa uvijek odgovara provjeri tijekom izvođenja.
Notes (EN)
This behavior requires TypeScript 5.5 or later (Inferred Type Predicates).
Bilješke (HR)
Ovo ponašanje zahtijeva TypeScript 5.5 ili noviji (Inferred Type Predicates).