as const 是一个 const 断言,它告诉 TypeScript 为一个值推断 最具体(字面量)、深度只读 的类型,而不是将其扩展。
ts
a = ;
obj = { : };
arr = [, ];
b = ;
obj2 = { : } ;
arr2 = [, ] ;
as const 是一个 const 断言,它告诉 TypeScript 为一个值推断 最具体(字面量)、深度只读 的类型,而不是将其扩展。
a = ;
obj = { : };
arr = [, ];
b = ;
obj2 = { : } ;
arr2 = [, ] ;
它做三件事:不进行任何扩展(保持字面量值)、使所有内容都变为 readonly,以及将数组转换为 元组。
从值列表派生联合类型(单一事实来源):
const ROLES = ["admin", "editor", "viewer"] as const;
type Role = typeof ROLES[number]; // "admin" | "editor" | "viewer"
// add a role to the array → the union updates automatically
为配置/状态保留字面量类型:
const action = { type: "INCREMENT", by: 1 } as const;
// action.type is "INCREMENT" (a literal), so it works in discriminated unions
// without as const it'd be `string`, breaking narrowing
as const 桥接了运行时值和精确类型。
它让你只需定义一次数据(一个数组/对象),然后从中派生出精确的字面量类型 — 这对于 action 类型、路由映射、配置和任何必须保持字面量而不扩展为 string 的判别联合标签都是无价的。