Rules Hub
Coding Rules Library
Prefer const assertions for literals over explicit type annotations
Use `as const` for literals in conditionals to preserve their specific type, enabling cleaner type inference without manual annotations.
Bad example
| 1 | type AccessLevel = 'read' | 'write'; |
| 2 |
|
| 3 | function getAccess(isAdmin: boolean, current: AccessLevel) { |
| 4 | // Explicit type annotation is verbose and acts as a manual guard |
| 5 | const access: AccessLevel = isAdmin ? 'write' : current; |
| 6 | return access; |
| 7 | } |
Explanation (EN)
Manually annotating the variable type (`: AccessLevel`) adds noise and redundancy. It forces you to maintain the type definition on the variable, rather than letting TypeScript verify compatibility through inference.
Objašnjenje (HR)
Ručno anotiranje tipa varijable (`: AccessLevel`) stvara nepotreban šum i redundanciju. To te prisiljava da održavaš definiciju tipa na varijabli, umjesto da pustiš TypeScriptu da provjeri kompatibilnost putem zaključivanja (inference).
Good example
| 1 | type AccessLevel = 'read' | 'write'; |
| 2 |
|
| 3 | function getAccess(isAdmin: boolean, current: AccessLevel) { |
| 4 | // 'as const' ensures 'write' is treated as a specific literal type |
| 5 | // TypeScript automatically infers 'access' is AccessLevel |
| 6 | const access = isAdmin ? 'write' as const : current; |
| 7 | return access; |
| 8 | } |
Explanation (EN)
Using `as const` ensures the literal is treated as the specific type `'write'` rather than a generic string. This enables precise type inference, making the explicit type annotation on the variable unnecessary.
Objašnjenje (HR)
Korištenje `as const` osigurava da se literal tretira kao specifičan tip `'write'`, a ne kao generički string. To omogućuje precizno zaključivanje tipova, čineći eksplicitnu anotaciju na varijabli nepotrebnom.