问题描述
为什么在TypeScript中编译以下内容?
Why does the following compile in TypeScript?
enum xEnum {
X1,X2
}
function test(x: xEnum) {
}
test(6);
它不会抛出错误吗?恕我直言,这种隐式转换在这里是错误的,不是吗?
Shouldn't it throw an error? IMHO this implicit cast is wrong here, no?
这是。
推荐答案
这是语言规范(3.2.7枚举类型):
This is part of the language specification (3.2.7 Enum Types):
因此,决定允许在个数字之间进行隐式转换
和 Enum
,反之亦然。
So the decision to allow implicit conversion between number
and Enum
and vice-versa is deliberate.
这意味着您需要确保值是有效的。
This means you will need to ensure the value is valid.
function test(x: xEnum) {
if (typeof xEnum[x] === 'undefined') {
alert('Bad enum');
}
console.log(x);
}
尽管您可能不同意该实现,但值得注意的是枚举是在以下三种情况下很有用:
Although you might not agree with the implementation, it is worth noting that enums are useful in these three situations:
// 1. Enums are useful here:
test(xEnum.X2);
// 2. ...and here
test(yEnum.X2);
然后3.-键入 test(
它将告诉您可以用来确保选择存在的枚举类型的枚举类型。
And 3. - when you type test(
it will tell you the enum type you can use to guarantee you pick one that exists.
这篇关于TypeScript:要枚举的隐式数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!