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).
Keep guaranteed fields non-nullable; fix the source instead of widening the type
Do not change a required field's type to allow null just because a bug upstream occasionally produces null. Keep the type honest to the contract and fix the source.
Bad example
| 1 | // A stale cache sometimes returns name = null, so the type was loosened |
| 2 | interface UserBadgeProps { |
| 3 | name: string | null; // widened to silence the symptom |
| 4 | avatar: string; |
| 5 | } |
| 6 |
|
| 7 | function UserBadge({ name, avatar }: UserBadgeProps) { |
| 8 | // every consumer now has to defend against a null that shouldn't exist |
| 9 | return <span>{name ?? 'Unknown'}</span>; |
| 10 | } |
Explanation (EN)
Widening `name` to `string | null` makes the type lie about the contract and pushes defensive `?? 'Unknown'` checks into every consumer, while the real bug (the cache producing null) stays unfixed.
Objašnjenje (HR)
Proširivanje `name` na `string | null` čini da tip laže o ugovoru i gura obrambene `?? 'Unknown'` provjere u svakog korisnika, dok stvarni bug (cache koji vraća null) ostaje nepopravljen.
Good example
| 1 | // name is guaranteed present by the data contract; fix the cache, keep type honest |
| 2 | interface UserBadgeProps { |
| 3 | name: string; |
| 4 | avatar: string; |
| 5 | } |
| 6 |
|
| 7 | function UserBadge({ name, avatar }: UserBadgeProps) { |
| 8 | return <span>{name}</span>; |
| 9 | } |
Explanation (EN)
Keeping `name: string` reflects the actual guarantee, so consumers stay simple and TypeScript will flag any real source of null at the boundary where it must be fixed.
Objašnjenje (HR)
Zadržavanje `name: string` odražava stvarnu garanciju, pa korisnici ostaju jednostavni, a TypeScript će označiti svaki stvarni izvor null vrijednosti na granici gdje se mora popraviti.
Exceptions / Tradeoffs (EN)
If the field genuinely can be absent by design (optional API data, not-yet-loaded state), then nullable is correct and consumers should handle it.
Iznimke / Tradeoffi (HR)
Ako polje stvarno može izostati po dizajnu (opcionalni API podaci, stanje koje još nije učitano), tada je nullable ispravan i korisnici ga trebaju obraditi.