As Const Tuples Freeze Literal Element Types
Widen or preserve tuple literals deliberately: plain arrays widen to primitives, as const keeps each element its literal type for lookup tables.
Code
// Without as const, literals widen: this is (string | number)[]
const route = ['/health', 200, 'ok'];
const widened: (string | number)[] = route;
// as const freezes each position: readonly ['/health', 200, 'ok']
const frozen = ['/health', 200, 'ok'] as const;
const exact: readonly ['/health', 200, 'ok'] = frozen;
type Route = typeof frozen;
const routePath: Route[0] = '/health';
const routeStatus: Route[1] = 200;
console.log('types preserved:', routePath, routeStatus);
// Lookup tables built from as const rows keep literal keys findable.
const exitCodes = {
timeout: 124,
usage: 64,
} as const;
type ExitCode = (typeof exitCodes)[keyof typeof exitCodes];
const code: ExitCode = 124;
console.log('exit code:', code, 'usage:', exitCodes.usage);
// These fail compilation — frozen tuples are readonly and literal:
// frozen[0] = '/other';
// code = 1;Output
Captured from a sandboxed run of this snippet in the build pipeline.
types preserved: /health 200
exit code: 124 usage: 64How the snippet works
The file’s state is a handful of top-level bindings: route, frozen, exitCodes.
The top-level object literal pins timeout, usage as plain values — no derivation, no imports behind them.
Caveats
- Every symbol it touches is a language built-in — nothing to fetch.
Applying it
The demo output is labeled (types preserved:, exit code:), so every printed line has a specific operation behind it.
Statements that matter
const frozen = ['/health', 200, 'ok'] as const;
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `route`, `frozen`, `exitCodes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.