Rules Hub

Coding Rules Library

← Back to all rules
fullstack ruleStack: typescript
typescripttype-inferenceconst-assertionclean-code

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.

PR: Feat/FCK-1561 - Adding Invoice Table to Minside #3570Created: Dec 8, 2025

Bad example

Old codets
1const 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

New codets
1const 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).