const assertions
| as const | |
| Tuple inference | |
| Frozen objects | |
| Instead of enums |
as const
as const freezes a value into its narrowest literal type. The string north stops widening to string.
Dir is the single value north, so only that exact string is accepted. Use it for fixed choices with one option.
const dir = "north" as const;
type Dir = typeof dir; // "north"
Tuple inference
Arrays get the tuple treatment plus readonly in one step. Length and element types are locked together.
Rgb is a readonly triple of 255, 0, and 0. Push or reassignment fails at compile time.
const rgb = [255, 0, 0] as const;
type Rgb = typeof rgb; // readonly [255, 0, 0]
console.log(rgb[0]); // 255
Frozen objects
Objects become deeply readonly with literal values. Config data can be shared without fear of mutation.
host stays the literal localhost and port stays 8080. Any write is rejected before the code ever runs.
const config = {
host: "localhost",
port: 8080,
} as const;
console.log(config.port); // 8080
Instead of enums
A const object plus indexed access replaces many enums. Keys give readable names while values stay plain strings.
Role is admin or guest with zero runtime cost beyond the object itself. Add a member once and every consumer sees it.
const Roles = {
Admin: "admin",
Guest: "guest",
} as const;
type Role = (typeof Roles)[keyof typeof Roles]; // "admin" | "guest"
const me: Role = "admin";
Next: tsc CLI
Article author: Arthur Isaev