TypeScript:隐式数字枚举转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25762823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:55:49  来源:igfitidea点击:

TypeScript: Implicit number to enum cast

castingtypescriptimplicit-cast

提问by duedl0r

Why does the following compile in TypeScript?

为什么以下内容会在 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?

它不应该抛出错误吗?恕我直言,这个隐式演员在这里是错误的,不是吗?

Here is the playground link.

这是游乐场链接

回答by Fenton

This is part of the language specification (3.2.7 Enum Types):

这是语言规范的一部分(3.2.7 枚举类型):

Enum types are assignable to the Number primitive type, and vice versa, but different enum types are not assignable to each other

枚举类型可分配给 Number 原始类型,反之亦然,但不同的枚举类型不可相互分配

So the decision to allow implicit conversion between numberand Enumand vice-versa is deliberate.

因此,允许在number和之间进行隐式转换的决定Enum是经过深思熟虑的。

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

And 3. - when you type test(it will tell you the enum type you can use to guarantee you pick one that exists.

和 3. - 当您输入时,test(它会告诉您枚举类型,您可以使用它来保证您选择一个存在的枚举类型。

回答by itmitica

No, it shouldn't. There is no type casting here, the base type behind them all is the same, integer.

不,不应该。这里没有类型转换,它们背后的基本类型都是相同的,整数。

typescript enum type checking works fine

打字稿枚举类型检查工作正常

Your complaint is about range value which, in this case, has nothing to do with type checking.

您的抱怨是关于范围值,在这种情况下,与类型检查无关。

enum is a flexible set of constants

枚举是一组灵活的常量

enum xEnum {X1=6, X2} // ruins it for test(0)