Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: typescript
typescripttypestype-safetyenumsinference

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.

PR: Feat/FCK-1575 - Map products to human readable for Invoice Table #3633Created: Dec 8, 2025

Bad example

Old codets
1// The keys are known (draft, published), but typed generically
2const 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
9const 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

New codets
1// Using 'as const' infers the exact literal keys
2const STATUS_LABELS = {
3 draft: 'Draft',
4 published: 'Published',
5} as const;
6
7export 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.