const Assertions and as const
Use as const to infer literal and tuple types precisely.
What Is as const?
as const is a type assertion that tells TypeScript to infer the most specific literal types possible for an expression, and to make all properties readonly.
const colors = ["red", "green", "blue"] as const;
// type: readonly ["red", "green", "blue"]Preventing Widening with as const
Without as const, string values in arrays and objects widen to string. With it, they stay as their literal types.
const dir1 = { direction: "left" };
// dir1.direction: string
const dir2 = { direction: "left" } as const;
// dir2.direction: "left"All lessons in this course
- Type Widening and Narrowing Mechanics
- Contextual Typing: Inference from Context
- Freshness and Excess Property Checking
- const Assertions and as const