Const Assertions Build Literal Lookup Tables

Freeze lookup tables with as const so keyof typeof yields exact key unions, arrays expose element unions, and Record mismatches fail at compile time.

TypescriptConfig Management

Code

typescriptsnippet
28 lines
// as const:对象与数组冻结成字面量类型 + readonly
const EXIT_CODES = {
  ok: 0,
  usage: 64,
  dataError: 65,
} as const;

type ExitReason = keyof typeof EXIT_CODES; // 'ok' | 'usage' | 'dataError'

const LEVELS = ['debug', 'info', 'warn', 'error'] as const;
type Level = (typeof LEVELS)[number]; // 'debug' | 'info' | 'warn' | 'error'

// 表与键联合互相校验:漏 key、拼错键名都在编译期报错
const MESSAGES: Record<ExitReason, string> = {
  ok: 'completed',
  usage: 'bad arguments',
  dataError: 'input failed validation',
};

function describeExit(reason: ExitReason): string {
  return `${MESSAGES[reason]} (exit ${EXIT_CODES[reason]})`;
}

const active: Level = 'warn';
console.log(describeExit('ok'));
console.log(describeExit('dataError'));
console.log('levels:', LEVELS.join(' < '));
console.log('active level:', active);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

completed (exit 0)
input failed validation (exit 65)
levels: debug < info < warn < error
active level: warn

Literal unions from tables

as const freezes EXIT_CODES into literal types, so keyof typeof EXIT_CODES is exactly ‘ok’ | ‘usage’ | ‘dataError’ and (typeof LEVELS)[number] is the four-level union. The type flows from the data instead of being declared separately.

Compile-time cross-checks

MESSAGES is typed Record<ExitReason, string>, so dropping or misspelling a key fails compilation — the table and the key union validate each other. describeExit reads both tables with the same union.

Runtime output

The demo prints the two describeExit results and the joined level ladder (debug < info < warn < error) plus the active level, showing that the type machinery adds no runtime cost.

Interactive Tools for This Topic

FAQ

How does Record<ExitReason, string> enforce completeness?
Record requires an entry for every member of the key union; omitting or misspelling one leaves the object literal without a matching property and compilation fails.
What does as const contribute to the key union?
It preserves literal types, so keyof typeof yields the exact key names rather than widening to string.