数字枚举
enum Direction {
Up = 1,
Down,
Left,
Right,
}
枚举成员会被赋值为从 0 开始递增的数字,同时也会对枚举值到枚举名进行反向映射:
console.log(Direction.Up); // 1
console.log(Direction[1]); // Up
当然我们可以手动赋值:
enum Direction {
Up = 10,
Down,
Left,
Right,
}
此时,Up
为 10,Down
为 11,依次类推。
它会被编译为:
var Direction;
(function (Direction) {
Direction[(Direction["Up"] = 10)] = "Up";
Direction[(Direction["Down"] = 11)] = "Down";
Direction[(Direction["Left"] = 12)] = "Left";
Direction[(Direction["Right"] = 13)] = "Right";
})(Direction || (Direction = {})); // 这里的 Direction || (Direction = {}) 是为了防止重复声明
字符串枚举
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
假如从服务器获取到的数据是 UP
,那么我们可以通过 Direction.Up
来获取到 UP
。
const value = "UP";
if (value === Direction.Up) {
// ...
}
常量枚举
const enum Direction {
Up,
Down,
Left,
Right,
}
使用常量枚举可以提升性能,因为它会在编译阶段被移除。
const enum Direction {
Up,
Down,
Left,
Right,
}
const value=1;
if (value === Direction.Up) {
// ...
}
编译后:
const value = 1;
if (value === 0 /* Up */) {
// ...
}