一、数字枚举
(用于命名一组常数,当一个变量多个取值,可列为枚举类型)
声明一个枚举类型,默认是数字类型,给第一个赋值,后面累加:
enum Direction {
Up,
Down=10,
Left,
Right
}
console.log(Direction.Up === 0); // true
console.log(Direction.Down === 10); // true
console.log(Direction.Left === 11); // true
console.log(Direction.Right === 12); // true二、字符串枚举
enum Direction {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
console.log(Direction['Right'], Direction.Up); // Right Up三、异构枚举(混合使用)
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",
}反向映射(枚举)
enum Direction {
Up,
Down,
Left,
Right
}
console.log(Direction[0]); // Up枚举的本质
把枚举看成一个对象
enum Direction {
Up = 10,
Down,
Left,
Right
}
console.log(Direction[10], Direction['Right']); // Up 13Direction[Direction["Up"] = 10] = "Up" 也就是 Direction[10] = "Up" ,所以我们可以把枚举类型看成一个JavaScript对象,而由于其特殊的构造,导致其拥有正反向同时映射的特性。
常亮枚举
枚举是可以被声明为常亮的,好处在于TypeScript能省略掉,优化性能。比如:
const enum Direction {
Up = "Up",
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
const a = Direction.Up;javascript在编译后,为:
var a = "Up";TypeScript 在这一步就把 Direction 去掉了,我们直接使用 Direction 的值即可,这是性能提升的一个方案。
枚举成员类型
当枚举成员拥有字面量枚举时,即有了特殊的语义,即枚举成员成为类型;
比如声明了数字类型:
enum Direction {
Up,
Down,
Left,
Right
}
const a = 0
console.log(a === Direction.Up) // tru我们把成员当做值使用,看来是没问题的,因为成员值本身就是0,那么我们再加几行代码:
type c = 0
declare let b: c
b = 1 // 不能将类型“1”分配给类型“0”
b = Direction.Up // ok 我们看到,上面的结果显示这个枚举的成员居然也可以被当做类型使用,这就是枚举成员当做类型使用的情况。
联合枚举类型
enum Direction {
Up,
Down,
Left,
Right
}
declare let a: Direction
enum Animal {
Dog,
Cat
}
a = Direction.Up // ok
a = Animal.Dog // 不能将类型“Animal.Dog”分配给类型“Direction”
我们把 a 声明为 Direction 类型,可以看成我们声明了一个联合类型 Direction.Up | Direction.Down | Direction.Left | Direction.Right,只有这四个类型其中的成员才符合要求。