[ts]枚举

47 阅读1分钟

官网链接

数字枚举

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

字符串枚举

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

联合枚举

enum ShapeKind {
    Circle,
    Square,
}

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

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

编译时的枚举

keyof typeof来获取类型

enum LogLevel {
    ERROR,
    WARN,
    INFO,
    DEBUG,
}

// type LogLevelStrings = 'ERROR' | 'WARN' | 'INFO' | 'DEBUG';
type LogLevelStrings = keyof typeof LogLevel;

反向映射

enum Enum {
    A,
}

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

会编译成

"use strict";

var Enum;

(function (Enum) {
    Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));

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

const 枚举

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

 

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

编译成

"use strict";

let directions = [
    0 /* Direction.Up */,
    1 /* Direction.Down */,
    2 /* Direction.Left */,
    3 /* Direction.Right */,
];