Skip to content

枚举类型

枚举的优势:可以直接使用枚举的键,获取枚举中定义的值

数字枚举

  • 默认情况下,枚举成员的值从 0 开始自动递增。
ts
enum Direction {
  Up,    // 0
  Down,  // 1
  Left,  // 2
  Right  // 3
}

console.log(Direction.Up);    // 0
console.log(Direction[2]);    // "Left"
  • 可以手动指定初始值,后续会递增:
ts
enum Direction {
  Up = 1,
  Down,    // 2
  Left,    // 3
  Right    // 4
}

字符串枚举

每个成员必须显式赋值,无法自动递增。

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

console.log(Direction.Up); // "UP"

枚举反向映射

反向映射:你可以通过枚举的值,反查出对应的枚举成员名。

ts
enum Color {
  Red,
  Green,
  Blue,
}

console.log(Color.Red)     // 输出: 0
console.log(Color[0])      // 输出: 'Red'
ts
"use strict";
var Color;
(function (Color) {
    Color[Color["Red"] = 0] = "Red";
    Color[Color["Green"] = 1] = "Green";
    Color[Color["Blue"] = 2] = "Blue";
})(Color || (Color = {}));

console.log(Color);  
/*
{
  0: "Red",
  1: "Green",
  2: "Blue",
  Red: 0,
  Green: 1,
  Blue: 2
}
*/
  • 字符串枚举没有反向映射
ts
enum Direction {
  Up = "UP",
  Down = "DOWN",
}
ts
"use strict";
var Direction;
(function (Direction) {
    Direction["Up"] = "UP";
    Direction["Down"] = "DOWN";
})(Direction || (Direction = {}));
ts
console.log(Direction.Up)    // 'UP'
console.log(Direction['UP']) // undefined ❌

示例

ts
enum Status {
  Pending,
  Success,
  Fail
}

function update(status: Status) {
  if (status === Status.Success) console.log("成功");
}
ts
enum EventType {
  Click = "click",
  Hover = "hover",
  Focus = "focus"
}

function handleEvent(type: EventType) { }
handleEvent(EventType.Click);