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).
Validate dynamic values with assert, not type casts
Narrow untyped/dynamic input (env vars, JSON, params) with runtime assertions instead of `as` casts, then drop the now-unneeded optional chaining.
Bad example
| 1 | const source = process.env.SOURCE ?? ''; |
| 2 | return (config as IConfigMap)[source]?.url; |
Explanation (EN)
The `as` cast just tells the compiler to trust a value it cannot verify; an unexpected SOURCE slips through and you fall back to undefined silently via optional chaining. The bug surfaces far from its cause.
Objašnjenje (HR)
`as` cast samo govori prevoditelju da vjeruje vrijednosti koju ne može provjeriti; neočekivani SOURCE prolazi i tiho završi kao undefined kroz optional chaining. Greška se onda pojavi daleko od svog uzroka.
Good example
| 1 | import assert from 'node:assert'; |
| 2 |
|
| 3 | const source = process.env.SOURCE; |
| 4 | assert(source, 'SOURCE is not set'); |
| 5 | assert( |
| 6 | source === 'local' || source === 'deploy' || source === 'preview', |
| 7 | `Unexpected SOURCE: "${source}"` |
| 8 | ); |
| 9 | return config[source].url; |
Explanation (EN)
The assertions both narrow the type for the compiler and throw loudly on bad input, so misconfiguration fails fast and obviously. Because `source` is now a known literal, the optional chaining is gone — no silent undefined.
Objašnjenje (HR)
Asercije istovremeno suzuju tip za prevoditelja i glasno bacaju iznimku na lošem ulazu, pa loša konfiguracija pada brzo i očito. Budući da je 'source' sada poznati literal, optional chaining je nestao — nema tihog undefined.
Notes (EN)
Safe to throw in development/startup paths. After a successful assert the value is a known type, so defensive `?.` and `?? fallback` on that value become redundant.
Bilješke (HR)
Bacanje iznimke je sigurno na razvojnim/startup putanjama. Nakon uspješne asercije vrijednost je poznatog tipa, pa obrambeni `?.` i `?? fallback` na toj vrijednosti postaju suvišni.