<返回目录     Powered by claud/xia兄

第9课: 枚举Enum

什么是枚举?

枚举是TypeScript提供的一种为一组数值赋予友好名称的方式。枚举可以让代码更具可读性和可维护性。

数字枚举

enum Direction {
  Up,      // 0
  Down,    // 1
  Left,    // 2
  Right    // 3
}

let dir: Direction = Direction.Up;
console.log(dir); // 0

// 自定义起始值
enum Direction2 {
  Up = 1,
  Down,    // 2
  Left,    // 3
  Right    // 4
}

// 完全自定义
enum HttpStatus {
  OK = 200,
  NotFound = 404,
  InternalServerError = 500
}

字符串枚举

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

let dir: Direction = Direction.Up;
console.log(dir); // "UP"

// 字符串枚举更具可读性
enum LogLevel {
  ERROR = "ERROR",
  WARN = "WARN",
  INFO = "INFO",
  DEBUG = "DEBUG"
}

异构枚举

枚举可以混合字符串和数字成员(不推荐):

enum BooleanLikeHeterogeneousEnum {
  No = 0,
  Yes = "YES"
}

计算成员和常量成员

enum FileAccess {
  // 常量成员
  None,
  Read = 1 << 1,
  Write = 1 << 2,
  ReadWrite = Read | Write,

  // 计算成员
  G = "123".length
}

反向映射

数字枚举支持反向映射(从值到名称):

enum Enum {
  A
}

let a = Enum.A;
let nameOfA = Enum[a]; // "A"

// 编译后的JavaScript代码
var Enum;
(function (Enum) {
  Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));

常量枚举

使用 const enum 定义常量枚举,编译时会被内联:

const enum Direction {
  Up,
  Down,
  Left,
  Right
}

let directions = [
  Direction.Up,
  Direction.Down,
  Direction.Left,
  Direction.Right
];

// 编译后
let directions = [0, 1, 2, 3];

外部枚举

declare enum Enum {
  A = 1,
  B,
  C = 2
}

枚举作为类型

enum ShapeKind {
  Circle,
  Square
}

interface Circle {
  kind: ShapeKind.Circle;
  radius: number;
}

interface Square {
  kind: ShapeKind.Square;
  sideLength: number;
}

let c: Circle = {
  kind: ShapeKind.Circle,
  radius: 100
};

枚举的实际应用

// HTTP状态码
enum HttpStatus {
  OK = 200,
  Created = 201,
  BadRequest = 400,
  Unauthorized = 401,
  NotFound = 404,
  InternalServerError = 500
}

function handleResponse(status: HttpStatus) {
  switch (status) {
    case HttpStatus.OK:
      console.log("Success!");
      break;
    case HttpStatus.NotFound:
      console.log("Resource not found");
      break;
    default:
      console.log("Unknown status");
  }
}

// 用户角色
enum UserRole {
  Admin = "ADMIN",
  User = "USER",
  Guest = "GUEST"
}

function checkPermission(role: UserRole) {
  if (role === UserRole.Admin) {
    return true;
  }
  return false;
}

枚举 vs 对象字面量

// 使用枚举
enum Color {
  Red,
  Green,
  Blue
}

// 使用对象字面量(替代方案)
const Color2 = {
  Red: 0,
  Green: 1,
  Blue: 2
} as const;

type Color2 = typeof Color2[keyof typeof Color2];
枚举的优势:
练习:
  1. 创建一个表示星期的数字枚举
  2. 创建一个表示订单状态的字符串枚举
  3. 使用常量枚举定义颜色值
  4. 实现一个函数,根据枚举值执行不同操作