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).
Do not cast away nullable identifiers
When an identifier is nullable in the type system, narrow or reject it explicitly before use instead of hiding the risk with a cast.
Bad example
| 1 | function buildSelectorItems(watchlists: UserWatchlist[]) { |
| 2 | return watchlists.map((watchlist) => ({ |
| 3 | value: watchlist.id as number, |
| 4 | label: watchlist.name, |
| 5 | })); |
| 6 | } |
Explanation (EN)
The cast suppresses a real possibility from the type system instead of handling it. If a nullable identifier leaks through, the code produces invalid selector items and the bug becomes harder to trace because the compiler was explicitly silenced.
Objašnjenje (HR)
Cast skriva stvarnu mogućnost koju tipovni sustav već signalizira umjesto da je obradi. Ako nullable identifikator procuri dalje, kod proizvodi neispravne stavke selektora, a bug je teže pratiti jer je kompajler namjerno ušutkan.
Good example
| 1 | function buildSelectorItems(watchlists: UserWatchlist[]) { |
| 2 | return watchlists |
| 3 | .filter((watchlist): watchlist is UserWatchlist & { id: number } => watchlist.id !== null) |
| 4 | .map((watchlist) => ({ |
| 5 | value: watchlist.id, |
| 6 | label: watchlist.name, |
| 7 | })); |
| 8 | } |
Explanation (EN)
The code narrows the nullable field before it becomes part of the UI contract. This keeps the runtime behavior explicit and lets TypeScript help enforce that every emitted selector item is valid.
Objašnjenje (HR)
Kod sužava nullable polje prije nego što postane dio UI ugovora. Time runtime ponašanje ostaje eksplicitno, a TypeScript može pomoći da svaka emitirana stavka selektora bude valjana.
Notes (EN)
Prefer narrowing at the boundary where nullable data first enters the flow. If null is a legitimate domain case, model it explicitly instead of coercing it away.
Bilješke (HR)
Preferiraj sužavanje na granici gdje nullable podaci prvi put ulaze u tok. Ako je null legitiman domena slučaj, modeliraj ga eksplicitno umjesto da ga prisilno ukloniš.
Exceptions / Tradeoffs (EN)
A cast is only acceptable when an earlier runtime invariant already guarantees non-null and that invariant is immediately visible in the same code path.
Iznimke / Tradeoffi (HR)
Cast je prihvatljiv samo kada raniji runtime invariant već jamči non-null vrijednost i taj invariant je odmah vidljiv u istoj grani koda.