Numeric enums
enum Direction {
// 不写 1 的话默认从 0 递增
Up = 1,
Down,
Left,
Right,
}
String enums
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
Heterogeneous enums (mixed)
可以用但最好不要用
enum BooleanLikeHeterogeneousEnum {
No = 0,
Yes = "YES",
}
Computed and constant members
每个 enum member 都有值, 要么是一个 constant, 要么是一个 computed
enum FileAccess {
// constant members
None,
Read = 1 << 1,
Write = 1 << 2,
ReadWrite = Read | Write,
// computed member
G = "123".length
}
Union enums and enum member types
枚举和枚举成员都可以当作类型使用
Enums at runtime, Reverse mappings
枚举最终会编译成 js 的一个对象,
对于 numeric enum 来说, 会进行 reverse mapping, 就是 k-v 或者 v-k 都可以访问到
string enum 不会进行 reverse mapping
// ts
enum E {
X, Y, Z
}
// js
var E;
(function (E) {
E[E["X"] = 0] = "X";
E[E["Y"] = 1] = "Y";
E[E["Z"] = 2] = "Z";
})(E || (E = {}));
const
enums
// ts
const enum Directions {
Up,
Down,
Left,
Right
}
let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]
// js
// const enum 在编译后不会生成一个对象, 使用的地方会之直接被 inlined 写死进去\
// 所以 const enum 只能使用 constant, 不能使用 computed
var directions = [0 /* Up */, 1 /* Down */, 2 /* Left */, 3 /* Right */];
Ambient enums
Ambient enums are used to describe the shape of already existing enum types.
不晓得什么鬼意思