实现说明
各个操作都建立在顶层绑定之上:route、frozen、exitCodes。
模块级对象字面量,键名固定:timeout、usage。
使用要点
- 跑完文件,输出里会留下标记——
types preserved:、exit code:。
常见问题
有需要管理的依赖吗?
没有。无需声明或安装任何依赖。 状态都挂在模块顶层:route、frozen、exitCodes。
核心语句
const frozen = ['/health', 200, 'ok'] as const;
代码示例
// 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;