Codectionary / Developer documentation / TypeScript

Literal Preservation with as const

A const assertion prevents literal widening and gives object properties readonly types and array literals readonly tuple types. Introduced in TypeScript 3.4, it is a compile-time operation, not a runtime deep freeze. Referenced mutable objects can remain mutable.

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.
  1. Expected result: The program prints State: running; the commented operations are rejected.
  2. The tuple preserves each element’s literal type.
  3. 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

Specifications & further reading