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).
Drop optional chaining once a value is narrowed to non-null
After a guard or narrowing has guaranteed a value is present, access it directly. Leftover optional chaining implies it might still be nullish and adds noise.
Bad example
| 1 | function label(user?: User) { |
| 2 | if (!user) return 'Guest'; |
| 3 | return user?.name?.toUpperCase(); |
| 4 | } |
Explanation (EN)
After the early return, user is definitely defined, so user?.name keeps suggesting it could be undefined and misleads the reader.
Objašnjenje (HR)
Nakon ranog povratka user je sigurno definiran, pa user?.name i dalje sugerira da bi mogao biti undefined i zavarava citatelja.
Good example
| 1 | function label(user?: User) { |
| 2 | if (!user) return 'Guest'; |
| 3 | return user.name.toUpperCase(); |
| 4 | } |
Explanation (EN)
Once the guard narrows user, direct access reflects the real types and removes pointless chaining.
Objašnjenje (HR)
Kada guard suzi user, izravan pristup odrazava stvarne tipove i uklanja nepotrebno ulancavanje.
Exceptions / Tradeoffs (EN)
Keep optional chaining for fields that are genuinely still optional after narrowing. Balance against prefer-optional-chaining-for-nested-access: drop the ?. once a guard or narrowing has already proven the value is present.
Iznimke / Tradeoffi (HR)
Zadrzi optional chaining za polja koja su stvarno jos uvijek opcionalna nakon suzavanja.