Numeric enums

  1. enum Direction {
  2. // 不写 1 的话默认从 0 递增
  3. Up = 1,
  4. Down,
  5. Left,
  6. Right,
  7. }

String enums

  1. enum Direction {
  2. Up = "UP",
  3. Down = "DOWN",
  4. Left = "LEFT",
  5. Right = "RIGHT",
  6. }

Heterogeneous enums (mixed)

可以用但最好不要用

  1. enum BooleanLikeHeterogeneousEnum {
  2. No = 0,
  3. Yes = "YES",
  4. }

Computed and constant members

每个 enum member 都有值, 要么是一个 constant, 要么是一个 computed

  1. enum FileAccess {
  2. // constant members
  3. None,
  4. Read = 1 << 1,
  5. Write = 1 << 2,
  6. ReadWrite = Read | Write,
  7. // computed member
  8. G = "123".length
  9. }

Union enums and enum member types

枚举和枚举成员都可以当作类型使用

Enums at runtime, Reverse mappings

枚举最终会编译成 js 的一个对象,
对于 numeric enum 来说, 会进行 reverse mapping, 就是 k-v 或者 v-k 都可以访问到
string enum 不会进行 reverse mapping

  1. // ts
  2. enum E {
  3. X, Y, Z
  4. }
  5. // js
  6. var E;
  7. (function (E) {
  8. E[E["X"] = 0] = "X";
  9. E[E["Y"] = 1] = "Y";
  10. E[E["Z"] = 2] = "Z";
  11. })(E || (E = {}));

const enums

  1. // ts
  2. const enum Directions {
  3. Up,
  4. Down,
  5. Left,
  6. Right
  7. }
  8. let directions = [Directions.Up, Directions.Down, Directions.Left, Directions.Right]
  9. // js
  10. // const enum 在编译后不会生成一个对象, 使用的地方会之直接被 inlined 写死进去\
  11. // 所以 const enum 只能使用 constant, 不能使用 computed
  12. 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.

不晓得什么鬼意思