打字稿中枚举的意义是什么

Nis*_*wal 2 typescript

打字稿中枚举的用途是什么。如果它的目的只是为了使代码可红,我们就不能为了同样的目的使用常量吗?

enum Color {
Red = 1, Green = 2, Blue = 4
};


let obj1: Color = Color.Red;
obj1 = 100; // does not show any error in IDE while enum should accept some specific values
Run Code Online (Sandbox Code Playgroud)

如果没有typechecking的优势,难道就不能这么写。

const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};

let obj2 = BasicColor.Red;
Run Code Online (Sandbox Code Playgroud)

Dan*_*ser 6

首先,在以下方面:

const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};
Run Code Online (Sandbox Code Playgroud)

Red, Green, 和Blue仍然是可变的(而它们不在枚举中)。


枚举还提供了一些东西:

  1. 一组封闭的众所周知的值(以后不允许打字错误),每个值都有......
  2. 每个成员都有一组各自的类似文字的类型,所有这些都提供......
  3. 通过包含所有值的单个命名类型

例如,要使用命名空间之类的东西来实现它,您必须执行以下操作

export namespace Color
    export const Red = 1
    export type Red = typeof Red;

    export const Green = 2;
    export type Green = 2;

    export const Blue = 3;
    export type Blue = typeof Blue;
}
export type Color = Color.Red | Color.Blue | Color.Green
Run Code Online (Sandbox Code Playgroud)

您还注意到一些不幸的遗留行为,其中 TypeScript 允许从任何数值分配到数字枚举。

但是,如果您使用的是字符串枚举,则不会出现这种行为。您还可以使用联合枚举启用其他功能,例如详尽检查:

enum E {
  Hello = "hello",
  Beautiful = "beautiful",
  World = "world"
}

// if a type has not been exhaustively tested,
// TypeScript will issue an error when passing
// that value into this function
function assertNever(x: never) {
  throw new Error("Unexpected value " + x);
}

declare var x: E;
switch (x) {
  case E.Hello:
  case E.Beautiful:
  case E.World:
    // do stuff...
    break;
  default: assertNever(x);
}
Run Code Online (Sandbox Code Playgroud)

  • @jcalz 可能,但老实说,我认为我不想用标志或新结构使事情进一步复杂化。所以请随意这样做,但我认为我们对此有所保留。 (2认同)