typescript - 打字稿枚举静态检查
问题描述
我仍然不确定如何理解打字稿枚举。
考虑一下:
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"
。
有人可以帮我理解吗?
具体来说,我正在研究为什么事情会这样工作的一些见解,有没有办法让编译器为我们检查事情?
解决方案
我在打字稿上问过 discord,显然,enum
s未被正式弃用。在联合类型和我们今天拥有的许多其他特性之前,语言中已经引入了枚举。
仅对于类型检查,可以使用文字联合类型,例如:
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
。唯一的缺点是声明比枚举更冗长,但我认为更好的类型检查和对运行时编码的额外控制是值得的。
推荐阅读
- functional-programming - 重载函数的 Hindley-Milner 类型推断
- javascript - 这段代码有什么问题?为什么它没有按我希望的方式工作..?
- http - 如何每5分钟自动重复一次我在fiddler中编写的http post请求?
- r - 如何使用 read.csv2.sql 在不解压缩的情况下读取 zip 文件?
- python - 通过 cx_Freeze 将 py 转换为 exe,启动时出现回溯错误
- python - 如何创建每行的列集不同的 Pandas 数据框?
- pandas - 在其他行的 31 天内有效地查找行
- python - 在 for 循环中连接 numpy 数组
- material-ui - 将 jss 类名添加到 jsx 元素数组
- python - 使用 Pandas 读取 excel 文件时跳过特定行