← 中文资源

简体中文版本

as const 元组冻结字面量元素类型

普通元组的字面量会拓宽成基础类型,as const 逐位冻结成只读字面量元组:索引访问 Route[0]/Route[1] 拿到精确类型,查找表也保持字面量键可追溯。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

types preserved: /health 200
exit code: 124 usage: 64

实现说明

各个操作都建立在顶层绑定之上: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;