打字稿中枚举的用途是什么。如果它的目的只是为了使代码可红,我们就不能为了同样的目的使用常量吗?
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)
    首先,在以下方面:
const BasicColor = {
    Red: 1,
    Green: 2,
    Blue: 4
};
Run Code Online (Sandbox Code Playgroud)
Red, Green, 和Blue仍然是可变的(而它们不在枚举中)。
枚举还提供了一些东西:
例如,要使用命名空间之类的东西来实现它,您必须执行以下操作
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)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           563 次  |  
        
|   最近记录:  |