Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: typescript
typescriptdrymaintainabilityconstantstypes

Derive union types from constant objects

Use `keyof typeof` to generate union types from constant objects to ensure a single source of truth and prevent synchronization errors.

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

Bad example

Old codets
1const STATUS_LABELS = {
2 draft: 'Draft',
3 published: 'Published',
4 archived: 'Archived',
5};
6
7// BAD: The type is manually defined and disconnected from the object.
8// If you add a key to STATUS_LABELS, you must remember to update this type.
9type ArticleStatus = 'draft' | 'published' | 'archived';
10
11export const getLabel = (status: ArticleStatus) => STATUS_LABELS[status];

Explanation (EN)

Manually defining a union type that mirrors the keys of an object creates a double maintenance burden. If the object changes but the type is not updated, it leads to bugs and inconsistency.

Objašnjenje (HR)

Ručno definiranje union tipa koji odražava ključeve objekta stvara dvostruki teret održavanja. Ako se objekt promijeni, a tip ne ažurira, to dovodi do grešaka i nekonzistentnosti.

Good example

New codets
1const STATUS_LABELS = {
2 draft: 'Draft',
3 published: 'Published',
4 archived: 'Archived',
5} as const;
6
7// GOOD: The type is derived directly from the keys of the constant object.
8// It automatically updates whenever the object changes.
9type ArticleStatus = keyof typeof STATUS_LABELS;
10
11export const getLabel = (status: ArticleStatus) => STATUS_LABELS[status];

Explanation (EN)

By using `as const` and `keyof typeof`, the configuration object becomes the Single Source of Truth. The type is automatically synchronized with the runtime values.

Objašnjenje (HR)

Korištenjem `as const` i `keyof typeof`, konfiguracijski objekt postaje jedini izvor istine (Single Source of Truth). Tip se automatski sinkronizira s runtime vrijednostima.