使用枚举作为类型允许枚举中不存在的值 [英] Using enums as types allows values that don't exist in the enum

查看:61
本文介绍了使用枚举作为类型允许枚举中不存在的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个打字稿代码(打字稿游乐场):

I have this typescript code (typescript playground):

const enum Something {
  None = 0,
  Email = 10,
  All = 20
}

const enum Other{
  Email = 10;
  Value = 15;
}

interface Foo {
  prop: Something
}
const value2: Something = Something.None;

// Why can 15 be assigned if it's not in the enum?
const value: Something = 15;

// This errors:
const otherValue: Something = 'asdf';

const value3: Something = Something.NotExists;

const value4: Something = Other.Value;

const value5: Something = Other.Email;

我不明白为什么在这种情况下 15 是可接受的值.15 不是枚举的值,所以不应该抛出吗?

I don't understand why 15 is an acceptable value in this caase. 15 is not a value of the enum, so shouldn't it throw?

推荐答案

(更新 2021-06-10,这没有被 针对联合枚举的 TS4.3 更新)

这是(可能令人惊讶的)预期行为.TypeScript 中的数字枚举有时用于按位运算,其中列出的值被视为 标志.而且,正如 @RyanCavanaugh评论报告的问题:

This is (maybe surprisingly) intended behavior. Numeric enums in TypeScript are sometimes used for bitwise operations, where the listed values are treated as flags. And, as stated by @RyanCavanaugh in a comment on a reported issue about this:

我们不区分标志和非标志枚举,因此高于[或不等于]任何给定枚举成员的数字不一定无效.例如

We don't distinguish between flag and non-flag enums, so a number that is above [or not equal to] any given enum member isn't necessarily invalid. For example

枚举标志{整洁 = 1,酷 = 2,很棒 = 4}//就像说 Neat |酷 |伟大的var x: Flags = 7;

因此即使 7 不等于任何一个列出的 Flags 枚举值,您仍然可以通过对列出的值执行按位运算来获得它.我很确定编译器除了检查值是否为 number 外,不会做任何限制.

So even though 7 is not equal to any one of the listed Flags enum values, you can still get it by performing bitwise operations of the listed values. I'm pretty sure that the compiler doesn't do any restriction other than checking that the value is a number.

在您的情况下,即使 Something 枚举值都不是 15,它也不会阻止您执行以下(无用且可疑的)以下操作:

In your case, even though none of the Something enumerated values are 15, it doesn't stop you from doing the (useless and dubiously sane) following:

const value: Something = (Something.Email | Something.All) >> 1;

相当于同一件事(10 | 20 的计算结果为 30,而 30 >> 1 的计算结果为 15).

which amounts to the same thing (10 | 20 evaluates to 30, and 30 >> 1 is 15).

请注意,这种按位的东西不适用于基于字符串的枚举,因此处理此问题的一种方法是将您的数字更改为字符串文字:

Note that this bitwise stuff doesn't apply to string-based enums, so one way to deal with this is to change your numbers to string literals:

const enum Something {
  None = '0',
  Email = '10',
  All = '20'
}
const value: Something = '15'; // error, as desired

并且编译器警告您 '15' 不是 Something 的有效值.

and the compiler warns you that '15' is not a valid value for Something.

希望有所帮助.祝你好运!

Hope that helps. Good luck!

这篇关于使用枚举作为类型允许枚举中不存在的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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