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 strict required fields over optional properties
Avoid marking all interface properties as optional; use strict types to guarantee the existence of core fields.
Bad example
| 1 | interface User { |
| 2 | id?: string; |
| 3 | username?: string; |
| 4 | email?: string; |
| 5 | avatarUrl?: string; |
| 6 | } |
| 7 |
|
| 8 | // Consumer code requires defensive checks for everything |
| 9 | function getUserLabel(user: User) { |
| 10 | if (!user.username) return 'Unknown'; |
| 11 | return user.username; |
| 12 | } |
Explanation (EN)
Marking essential fields like `id` or `username` as optional (`?`) weakens the type definition. It implies these fields might be missing entirely, forcing consumers to add redundant checks for data that is actually guaranteed.
Objašnjenje (HR)
Označavanje bitnih polja poput `id` ili `username` kao opcionalnih (`?`) slabi definiciju tipa. To implicira da ova polja mogu potpuno nedostajati, što prisiljava potrošače na suvišne provjere podataka koji zapravo sigurno postoje.
Good example
| 1 | interface User { |
| 2 | id: string; // Guaranteed to exist |
| 3 | username: string; // Guaranteed to exist |
| 4 | email: string; // Guaranteed to exist |
| 5 | avatarUrl: string | null; // Field exists but value can be null |
| 6 | } |
| 7 |
|
| 8 | // Consumer code can rely on the data contract |
| 9 | function getUserLabel(user: User) { |
| 10 | return user.username; |
| 11 | } |
Explanation (EN)
Core fields are marked as required, reflecting the actual data guarantee. Nullable fields are typed with `| null` instead of `?`, making the distinction between 'missing field' and 'empty value' explicit.
Objašnjenje (HR)
Ključna polja su označena kao obavezna, odražavajući stvarnu garanciju podataka. Polja koja mogu biti prazna tipizirana su s `| null` umjesto `?`, čime se jasno razlikuje 'nedostajuće polje' od 'prazne vrijednosti'.
Notes (EN)
Only use `?` if the API might omit the key entirely. If the key is always sent but might be empty, use `| null`.
Bilješke (HR)
Koristite `?` samo ako API može potpuno izostaviti ključ. Ako se ključ uvijek šalje, ali može biti prazan, koristite `| null`.