Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Prefer instanceof over Boolean for type narrowing
Use instanceof checks in filter callbacks to allow TypeScript to automatically infer types and avoid manual type predicates.
Bad example
| 1 | const signals: (AbortSignal | null | undefined)[] = [/* ... */]; |
| 2 |
|
| 3 | // Requires explicit type predicate to tell TS what happened |
| 4 | const activeSignals = signals.filter((signal): signal is AbortSignal => { |
| 5 | return Boolean(signal); |
| 6 | }); |
Explanation (EN)
Using `Boolean(signal)` relies on generic truthiness and requires a manual type predicate (`signal is AbortSignal`) to ensure the array type is narrowed correctly. It incorrectly suggests that any truthy value is valid.
Objašnjenje (HR)
Korištenje `Boolean(signal)` oslanja se na generičku istinitost i zahtijeva ručni predikat tipa (`signal is AbortSignal`) kako bi se osiguralo ispravno sužavanje tipa niza. Pogrešno sugerira da je bilo koja istinita vrijednost valjana.
Good example
| 1 | const signals: (AbortSignal | null | undefined)[] = [/* ... */]; |
| 2 |
|
| 3 | // TS automatically infers 'AbortSignal[]' (in TS 5.5+) |
| 4 | const activeSignals = signals.filter((signal) => { |
| 5 | return signal instanceof AbortSignal; |
| 6 | }); |
Explanation (EN)
Using `instanceof` provides a precise runtime check. Modern TypeScript (5.5+) can automatically infer the type predicate from this check, eliminating the need for manual annotations and preventing casting errors.
Objašnjenje (HR)
Korištenje `instanceof` pruža preciznu provjeru u vremenu izvođenja. Moderni TypeScript (5.5+) može automatski zaključiti predikat tipa iz ove provjere, eliminirajući potrebu za ručnim anotacijama i sprječavajući greške pri pretvorbi.
Notes (EN)
Inferred type predicates from filter functions were introduced in TypeScript 5.5.
Bilješke (HR)
Izvedeni predikati tipova iz funkcija filtriranja uvedeni su u TypeScript 5.5.