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).
Guard every level of an optional chain, not just the last property
Add `?.` at every level that can be missing, not only the final property being read.
Bad example
| 1 | function getHighResUri(asset: { renditions?: { highRes?: { uri: string } } }) { |
| 2 | // only the leaf is guarded — if `renditions` itself is undefined this still throws |
| 3 | if (!asset.renditions.highRes?.uri) { |
| 4 | return undefined; |
| 5 | } |
| 6 | return asset.renditions.highRes.uri; |
| 7 | } |
Explanation (EN)
This partially fixes the reported crash: it protects against `highRes` being missing, but `asset.renditions` is still accessed with a bare dot, so when `renditions` itself is absent (a very common shape when it comes from a source that prunes empty objects) the same TypeError is thrown, just one property earlier.
Objašnjenje (HR)
Ovo samo djelomično rješava prijavljeni pad aplikacije: štiti od nedostajućeg `highRes`, ali `asset.renditions` se i dalje čita direktno bez `?.`, pa kad sam `renditions` ne postoji (vrlo čest slučaj kad podaci dolaze iz izvora koji briše prazne objekte) i dalje puca isti TypeError, samo jedno svojstvo ranije.
Good example
| 1 | function getHighResUri(asset: { renditions?: { highRes?: { uri: string } } }) { |
| 2 | if (!asset.renditions?.highRes?.uri) { |
| 3 | return undefined; |
| 4 | } |
| 5 | return asset.renditions.highRes.uri; |
| 6 | } |
Explanation (EN)
Every level of the chain that can legitimately be missing gets its own `?.`, so the guard actually covers all the shapes the data can arrive in, not just the one the original bug report happened to mention.
Objašnjenje (HR)
Svaka razina lanca koja realno može nedostajati dobiva svoj `?.`, pa provjera zaista pokriva sve moguće oblike podataka, a ne samo onaj koji je spomenut u originalnoj prijavi bug-a.
Notes (EN)
When fixing a null/undefined crash, reproduce the exact production data shape first (including intermediate objects being absent, not just leaf properties) rather than patching only the property named in the stack trace.
Bilješke (HR)
Kod rješavanja pada zbog null/undefined vrijednosti prvo reproduciraj točan oblik podataka iz produkcije (uključujući nedostajanje međuobjekata, ne samo krajnjih svojstava), umjesto da zakrpaš samo svojstvo spomenuto u stack trace-u.