enum 定义了一组命名常量的集合。TypeScript 支持数字 enums 和字符串 enums。
ts
{ , , , }
.;
[];
{
= ,
= ,
}
.;
enum 定义了一组命名常量的集合。TypeScript 支持数字 enums 和字符串 enums。
{ , , , }
.;
[];
{
= ,
= ,
}
.;
与大多数 TypeScript 类型不同(它们在编译时消失),常规 enum 会向你的 bundle 中发出一个 JavaScript 对象。这就是为什么许多团队更喜欢字符串字面量的联合加上 as const,这是纯类型级别的:
// often preferred — zero runtime cost, easy to read in logs
const Status = { Active: "ACTIVE", Inactive: "INACTIVE" } as const;
type Status = typeof Status[keyof typeof Status]; // "ACTIVE" | "INACTIVE"
// or simply:
type Direction = "up" | "down" | "left" | "right";
const enum E { A, B } // inlined at compile time — no runtime object, but has tooling caveats
Enums 为固定集合(状态、角色、方向)赋予有意义的名称,并将它们分组到一个命名空间中。
但由于它们会生成运行时代码并具有一些特性(数字 enums 检查不严格),现代 TypeScript 通常在简单情况下采用字符串字面量联合——它们更轻量级且可以自然序列化。
当你想要命名空间或反向映射时,使用 enums。