TypeScript:要枚举的隐式数字 [英] TypeScript: Implicit number to enum cast

查看:84
本文介绍了TypeScript:要枚举的隐式数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在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):


枚举类型可分配给Number基本类型,反之
,但是不同的枚举类型不能互相分配

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

因此,决定允许在个数字之间进行隐式转换 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:要枚举的隐式数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆