首页 > 解决方案 > 打字稿枚举静态检查

问题描述

我仍然不确定如何理解打字稿枚举。

考虑一下:

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"

有人可以帮我理解吗?

具体来说,我正在研究为什么事情会这样工作的一些见解,有没有办法让编译器为我们检查事情?

标签: typescriptenums

解决方案


我在打字稿上问过 discord,显然,enums未被正式弃用。在联合类型和我们今天拥有的许多其他特性之前,语言中已经引入了枚举。

仅对于类型检查,可以使用文字联合类型,例如:

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';

或者做更复杂的事情,比如将键与你不能用 plain 做的功能相关联enum。唯一的缺点是声明比枚举更冗长,但我认为更好的类型检查和对运行时编码的额外控制是值得的。


推荐阅读