Syntax
const states = ["idle", "running"] as const;
type State = typeof states[number];Examples
Literal Preservation with as const: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints State: running; the commented operations are rejected.
const states = ["idle", "running", "done"] as const;
type State = typeof states[number];
function report(state: State): string { return `State: ${state}`; }
console.log(report(states[1]));
// states.push("failed"); // Type error: readonly tuple.
// report("missing"); // Type error: not an allowed literal.- Expected result: The program prints State: running; the commented operations are rejected.
- The tuple preserves each element’s literal type.
- Indexing its type with number derives the allowed state union from one source of truth.
Best practices
- Use as const for stable configuration literals and discriminants.
- Use runtime freezing separately when runtime mutation must be restricted.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook