Enum
一句话解释
enum 是 TypeScript feature 那个定义设置的 named constants, 要么 numeric or 字符串-based, 制作 code 更多 readable and self-documenting.
用大白话说
enum gives friendly names 到设置的 值. 例如, enum Direction { Up, Down, Left, Right } lets 你 use Direction.Up instead of magic numbers like 0.
Numeric enums auto-assign values starting at 0. String enums require explicit string values. Unlike most TypeScript features, enums are NOT erased — they compile to real JavaScript objects that exist at runtime.
Enums are useful for representing a fixed set of options: directions, statuses, colors, error codes. However, string literal unions (类型 方向 = "上" | "下") are often preferred for being simpler and fully erased.
示例
enum Status { Active, Inactive, Pending }
console.log(Status.Active); // 0
enum Color { Red = "RED", Green = "GREEN" }
console.log(Color.Red); // "RED"Numeric enums auto-increment 从 0. 字符串 enums 需要 explicit 值.
相关术语
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。