使用枚举作为类型允许值在枚举中不存在

使用枚举作为类型允许值在枚举中不存在

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

问题描述

我有此打字稿代码(打字机游乐场):

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?

推荐答案

(可能令人惊讶)这是预期的行为.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:

枚举标志{整洁= 1,酷= 2,好= 4}//喜欢说整洁|酷伟大的var x:Flags = 7;

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

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!

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

08-14 06:01