ts的枚举怎么写

时间:2025-03-26 15:20:58

在 TypeScript 中,枚举(enum)用于定义一组命名的常量:


1. 基础数字枚举

默认从 0 开始自动递增:

enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}
console.log(Direction.Up); // 输出: 0
console.log(Direction[0]); // 输出: "Up"(反向映射)

手动指定起始值

enum StatusCode {
  Success = 200,
  NotFound = 404,
  ServerError = 500
}
console.log(StatusCode.Success); // 200

2. 字符串枚举

所有成员必须显式初始化:

enum LogLevel {
  Info = "INFO",
  Warn = "WARN",
  Error = "ERROR"
}
console.log(LogLevel.Error); // "ERROR"
// 注意:字符串枚举无反向映射!

3. 常量枚举(const enum

编译时内联,不生成实际对象:

const enum Keys {
  Enter = 13,
  Escape = 27
}
let keyCode = Keys.Enter; // 编译后变为 let keyCode = 13

4. 异构枚举(混合类型,不推荐)

混合数字和字符串成员:

enum Mixed {
  Yes = 1,
  No = "NO"
}
console.log(Mixed.Yes); // 1
console.log(Mixed.No);  // "NO"

5. 计算成员(仅限非常量枚举)

在非 const 枚举中允许计算值:

enum FileAccess {
  Read = 1 << 1,    // 2
  Write = 1 << 2,   // 4
  ReadWrite = Read | Write // 6
}
console.log(FileAccess.ReadWrite); // 6

6. 枚举作为类型

定义枚举类型变量:

enum UserRole {
  Admin = "admin",
  User = "user"
}

function setRole(role: UserRole): void {
  // ...
}

setRole(UserRole.Admin); // 正确
setRole("guest");       // 错误:类型不匹配

最佳实践

  1. 优先使用字符串枚举
    提升代码可读性,避免数字的魔法值:

    enum ApiEndpoint {
      Users = "/api/users",
      Posts = "/api/posts"
    }
    
  2. 避免异构枚举
    保持枚举成员类型一致,增强可维护性。

  3. 常量枚举优化性能
    高频使用的枚举使用 const enum 减少运行时开销:

    const enum Priority {
      Low,
      Medium,
      High
    }
    
  4. 导出枚举供外部使用
    模块化场景下导出枚举:

    export enum Theme {
      Light = "light",
      Dark = "dark"
    }
    

编译结果对比

普通数字枚举

enum Direction { Up, Down }

编译为

var Direction;
(function (Direction) {
  Direction[Direction["Up"] = 0] = "Up";
  Direction[Direction["Down"] = 1] = "Down";
})(Direction || (Direction = {}));

常量枚举

const enum Keys { Enter = 13 }
let key = Keys.Enter;

编译为

let key = 13; // 无 Direction 对象

通过合理使用枚举,可以提升代码的可读性和类型安全性。