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

查看:30
本文介绍了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 Enum Types)的一部分:

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

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

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

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

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天全站免登陆