打字稿枚举静态检查
Typescript enum static checking
我仍然不确定如何理解打字稿枚举。
考虑一下:
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"
.
不兼容
有人可以帮我理解吗?
具体来说,我正在寻找一些关于为什么事情会这样工作的见解,有没有办法让编译器为我们检查事情?
我在 typescript discord 询问过,显然 enum
已 正式弃用。 before 联合类型和我们今天拥有的许多其他功能中引入了枚举。
仅用于类型检查,可以使用文字联合类型,例如:
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
无法做到的功能相关联。唯一的缺点是声明比枚举更冗长,但我认为更好的类型检查和对运行时编码的额外控制是值得的。
我仍然不确定如何理解打字稿枚举。
考虑一下:
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"
.
有人可以帮我理解吗?
具体来说,我正在寻找一些关于为什么事情会这样工作的见解,有没有办法让编译器为我们检查事情?
我在 typescript discord 询问过,显然 enum
已 正式弃用。 before 联合类型和我们今天拥有的许多其他功能中引入了枚举。
仅用于类型检查,可以使用文字联合类型,例如:
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
无法做到的功能相关联。唯一的缺点是声明比枚举更冗长,但我认为更好的类型检查和对运行时编码的额外控制是值得的。