Rules Hub
Coding Rules Library
Freeze static collections with const assertions
Use `as const` on static arrays and objects to infer literal types and read-only tuples, preventing type widening.
Bad example
| 1 | const ROLES = ['admin', 'editor', 'viewer']; |
| 2 | // Inferred as string[]. |
| 3 | // We cannot derive the specific 'Role' union type from this, |
| 4 | // and TypeScript won't prevent pushing new strings to it. |
Explanation (EN)
Defining an array without `as const` widens the type to `string[]`, losing the specific values and allowing mutation. This makes it impossible to use the values as a source of truth for types.
Objašnjenje (HR)
Definiranje niza bez `as const` proširuje tip na `string[]`, čime se gube specifične vrijednosti i omogućuje mutacija. To onemogućuje korištenje tih vrijednosti kao izvora istine za tipove.
Good example
| 1 | const ROLES = ['admin', 'editor', 'viewer'] as const; |
| 2 | // Inferred as readonly ["admin", "editor", "viewer"]. |
| 3 | // Allows deriving types: type Role = typeof ROLES[number]; |
Explanation (EN)
`as const` locks the array as a read-only tuple of specific literals. This enables strict type checking and allows you to derive union types directly from the implementation (Single Source of Truth).
Objašnjenje (HR)
`as const` zaključava niz kao `read-only` tuple specifičnih literala. To omogućuje strožu provjeru tipova i izvođenje unija tipova izravno iz implementacije (Single Source of Truth).