Rules Hub
Coding Rules Library
Prefer specific union keys over generic string index signatures
Avoid typing maps as `Record<string, T>` when the keys are a finite known set; use `as const` or explicit unions to enforce strict key validation.
Bad example
| 1 | // The keys are known (draft, published), but typed generically |
| 2 | const STATUS_LABELS: Record<string, string> = { |
| 3 | draft: 'Draft', |
| 4 | published: 'Published', |
| 5 | }; |
| 6 |
|
| 7 | // TypeScript allows this typo because the key is just 'string' |
| 8 | // This returns 'undefined' at runtime but TS thinks it is a string |
| 9 | const label = STATUS_LABELS['publised']; |
Explanation (EN)
Using `Record<string, string>` tells TypeScript that *any* string is a valid key. This disables type checking for typos or missing keys, leading to potential runtime errors when accessing undefined properties.
Objašnjenje (HR)
Korištenje `Record<string, string>` govori TypeScriptu da je *bilo koji* string valjan ključ. To onemogućuje provjeru tipfelera ili nedostajućih ključeva, što vodi do potencijalnih runtime grešaka pri pristupu nedefiniranim svojstvima.
Good example
| 1 | // Using 'as const' infers the exact literal keys |
| 2 | const STATUS_LABELS = { |
| 3 | draft: 'Draft', |
| 4 | published: 'Published', |
| 5 | } as const; |
| 6 |
|
| 7 | export type StatusKey = keyof typeof STATUS_LABELS; |
| 8 |
|
| 9 | // TypeScript catches the typo immediately |
| 10 | // const label = STATUS_LABELS['publised']; // Error: Property does not exist |
Explanation (EN)
Using `as const` (or an explicit union type) restricts the object keys to a specific set of values. This enables TypeScript to validate access strictly, preventing typos and enabling better autocomplete.
Objašnjenje (HR)
Korištenje `as const` (ili eksplicitnog union tipa) ograničava ključeve objekta na specifičan skup vrijednosti. To omogućuje TypeScriptu strogu provjeru pristupa, sprječava tipfelere i omogućuje bolje automatsko dovršavanje.