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 explicit null over conditional object spreading
Ensure consistent object shapes by assigning `null` to missing properties instead of conditionally omitting the key using spread syntax.
Bad example
| 1 | return items.map((item) => { |
| 2 | // Bad: Variable used for conditional spread |
| 3 | const metadata = item.meta ? format(item.meta) : null; |
| 4 |
|
| 5 | return { |
| 6 | id: item.id, |
| 7 | name: item.name, |
| 8 | // Bad: The 'metadata' key is completely missing if null |
| 9 | ...(metadata ? { metadata } : {}), |
| 10 | }; |
| 11 | }); |
Explanation (EN)
Using conditional spreading `...(value ? { key } : {})` results in an inconsistent object shape where keys may be missing entirely. This forces consumers to check for key existence instead of just value nullability and prevents JavaScript engines from optimizing object structures (hidden classes).
Objašnjenje (HR)
Korištenje uvjetnog širenja `...(value ? { key } : {})` rezultira nekonzistentnim oblikom objekta gdje ključevi mogu potpuno nedostajati. To prisiljava potrošače da provjeravaju postojanje ključa umjesto samo nullabilnosti vrijednosti i sprječava JavaScript engine da optimizira strukture objekata.
Good example
| 1 | return items.map((item) => ({ |
| 2 | id: item.id, |
| 3 | name: item.name, |
| 4 | // Good: Key always exists, value is explicitly null if missing |
| 5 | metadata: item.meta ? format(item.meta) : null, |
| 6 | })); |
Explanation (EN)
Assigning `null` explicitly ensures the object always has the same keys (consistent shape). This satisfies strict TypeScript interfaces (e.g., `metadata: Meta | null`) and simplifies frontend logic, as developers can rely on the key being present.
Objašnjenje (HR)
Eksplicitno dodjeljivanje `null` osigurava da objekt uvijek ima iste ključeve (konzistentan oblik). To zadovoljava stroga TypeScript sučelja (npr. `metadata: Meta | null`) i pojednostavljuje frontend logiku, jer se programeri mogu osloniti na prisutnost ključa.