我仍然不确定如何理解打字稿枚举。
考虑一下:
enum Int { a, b };
const array: Int[] = [];
array.push(Int.a); // ok
array.push(0); // same
array.push(1); // this is b
array.push(123); // works
array.push(-3e6); // also works
所以任何 number
都兼容 Int
??
我知道我可以动态检查,因为 enum
声明也会生成对象声明,除非我们使用 const enum
。但我期望静态类型为 0 | 1
而不是 number
。
现在是字符串枚举:
enum Str { a = 'a', b = 'b' };
const array: Str[] = [];
array.push(Str.a); // ok
array.push('a'); // fails
因此,根据上一个示例,人们可能会认为 Str
会与 string
兼容,但事实并非如此。它与 "a" | "b"
事件不兼容。
有人能帮我弄清楚吗?
具体来说,我正在寻找一些关于为什么事情会这样工作的见解,有没有办法让编译器为我们检查事情?
答案 0 :(得分:0)
我在 typescript discord 询问过,显然 enum
已未正式弃用。在联合类型和我们今天拥有的许多其他功能之前,已经在语言中引入了枚举。
仅用于类型检查,可以使用文字联合类型,例如:
type Int = 0 | 1;
或
type Str = 'a' | 'b';
如果您还需要运行时检查,您可以将运行时对象声明为 const
,然后使用 typeof
构建类型。这比枚举更灵活,因为您可以选择如何对运行时对象进行编码。
以数组为例:
const colors = ['red', 'green', 'blue'] as const;
type Color = typeof colors[number]; // 'red' | 'green' | 'blue'
或者作为地图:
const colors = {
red: '#ff0000',
green: '#00ff00',
blue: '#0000ff'
} as const;
type Color = keyof typeof colors; // 'red' | 'green' | 'blue';
或者做更复杂的事情,例如将键与您无法使用普通 enum
完成的功能相关联。唯一的缺点是声明比枚举更冗长,但我认为更好的类型检查和对运行时编码的额外控制是值得的。