- All Courses
- TypeScript Deep Dive
- The Type System Underneath
- Literal types and const assertions
Literal types and const assertions
By default a literal assigned to a mutable binding widens to its base type, because the binding could later hold any string.
Overview
Widening, and how to stop it
By default a literal assigned to a mutable binding widens to its base type, because the binding could later hold any string. That is usually what you want and occasionally exactly what you do not.
A const assertion stops the widening: properties become readonly, arrays become tuples, and every literal keeps its exact type. It is the standard way to define a set of allowed values once and use it in both worlds.
From such an array you can derive the union of its members, so the runtime list and the type stay in sync automatically. Adding a value in one place updates both.
In this lesson you will:
- Keep a literal from widening to string
- Freeze an object or array into exact types
- Derive a union from a runtime array
Resources
Notes are not saved yet — they clear when you leave this page.
Unions, intersections, and narrowing
3m
unknown, never, and the any escape hatch
8m