Enums in TypeScript
定义 named 常量设置使用 numeric and 字符串 enums, and 当到 prefer alternatives.
你将学到
- 如何 定义 numeric and 字符串 enums
- difference 之间 enum 成员 and 它们的值
- Reverse 映射 in numeric enums
- 当到 use 字符串 literal unions 相反的 enums
概念讲解
Numeric and String Enums
enum 是一种way to define a set of named constants。 A numeric enum assigns sequential numbers by default: enum 方向 { 上, 下, 左, 正确 } gives Up=0, Down=1, etc. A string enum uses explicit string values: enum 状态 { Active = "ACTIVE", Inactive = "INACTIVE" }. String enums are generally preferred because the compiled output is self-documenting and immune to reordering.
How Enums Compile
Numeric enums generate a JavaScript object with both forward and reverse mappings — you can go from name to value and from value to name. String enums only generate forward mappings. This reverse mapping in numeric enums can be surprising and is another reason to prefer string enums. The compiled enum object exists at runtime, unlike type aliases which are erased entirely.
Enums vs Alternatives
For simple sets of string constants, a string literal union (类型 状态 = "active" | "inactive") is often better than an enum: it has no runtime overhead, works naturally with switch statements, and produces cleaner compiled output. Use enums when you need the runtime object (e.g. iterating over values) or when you want the self-documenting nature of named enum members in your API.
示例代码
// Numeric enum — values are 0, 1, 2, 3 by default.
enum Direction {
Up = 0,
Down = 1,
Left = 2,
Right = 3,
}
// String enum — explicit string values, preferred for clarity.
enum Status {
Active = "ACTIVE",
Inactive = "INACTIVE",
Pending = "PENDING",
}
function handleStatus(status: Status): string {
switch (status) {
case Status.Active:
return "User is active";
case Status.Inactive:
return "User is inactive";
default:
return "Unknown status";
}
}
const current: Status = Status.Pending;
console.log(handleStatus(current));
console.log(Direction.Up, Direction.Left);
Numeric enums auto-assign 数字 and support reverse 映射. 字符串 enums use explicit 值 and 是 clearer. Consider 字符串 literal unions for 零-运行时-cost alternatives.
动手试一试
- JSON 到 TypeScript
See 如何 enum-如字符串字段 in JSON become union 类型.
- Code Minifier
Observe 如何 enums 编译到 运行时对象对比 erased 类型.
常见错误
错误写法
Relying on numeric enum auto-incrementing and 然后 reordering 成员
正确做法
Reordering numeric enum 成员更改它们的值, 哪个能 break serialized 数据. Use 字符串 enums or explicitly assign numeric 值到 prevent accidental 更改.
错误写法
Using const enum 跨越包 边界
正确做法
Const enums 是 inlined at 编译时间 and 能 break 当 consumed 通过不同包. Use regular enums or 字符串 literal unions for shared code.
练习 Enums in TypeScript
8 个练习
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。