The Power of as const in TypeScript: From Tuples to Enums
Use as const for literal arrays and enums to preserve type safety and enable tuple inference.
Use as const for literal arrays and enums to preserve type safety and enable tuple inference.
Summary
The article explains how the TypeScript assertion "as const" preserves literal types, turning arrays into readonly tuples and objects into readonly properties with literal values. It demonstrates that without "as const", an array like ["click", "key"] is inferred as string[], losing positional information. By asserting "as const", the compiler infers a readonly tuple ["click", "key"], enabling precise destructuring and type narrowing.
The author then shows how "as const" can replace traditional TypeScript enums. A frozen object with string values, asserted as const, provides both runtime values and compile‑time type safety, avoiding the reverse mapping and tree‑shaking issues of enums. The pattern is applied to a status object, yielding a union type "pending" | "active" | "archived" | "deleted" that is serializable and type‑safe.
Two patterns are highlighted: literal‑type tuples for fixed‑shape data like coordinates, and const‑enum replacements for serializable status values. The article stresses that "as const" is a simple, powerful tool that can improve type safety and developer experience across a codebase.
Key changes
- as const narrows arrays to readonly tuples
- string literals remain literal, not widened to string
- object properties become readonly with literal types
- pattern 1: literal‑type tuples preserve positional info
- pattern 2: const‑enum replacement uses frozen object with as const
- runtime value is a plain object, serializable
- tree‑shaking is efficient
- as const improves type safety and developer experience