枚举

155 阅读1分钟

使用枚举我们可以定义一些带名字的常量。 使用枚举可以清晰地表达意图或创建一组有区别的用例。 TypeScript支持数字的和基于字符串的枚举。

数字枚举

我们可以使用enum关键字去声明一个枚举类型,数字枚举会根据值进行递增

enum Test {
    Up = 1,
    Down,
    Left,
    Right
}

如上,我们定义了一个数字枚举, Up使用初始化为 1。 其余的成员会从 1开始自动增长。 换句话说, Test.Up的值为 1, Down为 2, Left为 3, Right为 4

enum Test {
    Up,
    Down,
    Left,
    Right
}

不使用默认值的开头为1

字符串枚举

在一个字符串枚举里,每个成员都必须用字符串字面量,或另外一个字符串枚举成员进行初始化。

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right='RIGHT',
}
console.log(Direction.Right)  //RIGHT
异构枚举

枚举可以混合字符串和数字

enum Direction {
    Up = "UP",
    Down = 1,
    Left,
    Right,
}

console.log(Direction.Right)//3

down的值为3,所以后面的值会递增

联合枚举与枚举成员的类型

声明类型我们可以使用枚举来约束

enum Direction {
    Up = "UP",
    Down = 1,
    Left,
    Right,
}

interface testFace{
    x:Direction,
    y:number
}

const test:testFace={
    x:Direction.Left,
    y:1
}
运行时的枚举
enum E {
    X, Y, Z
}

function f(obj: { X: number }) {
    return obj.X;
}

console.log(f(E))
反向映射

我们可以用属性名去访问拿到属性值,也可以用属性值去拿到属性名

enum E {
    X, Y, Z
}

console.log(E[0]) //X
console.log(E['X']) //0