检查TypeScript中的枚举值是否存在 [英] Check if value exists in enum in TypeScript
本文介绍了检查TypeScript中的枚举值是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到一个号码 type = 3
,并检查是否存在于此枚举中:
I recieve a number type = 3
and have to check if it exists in this enum:
export const MESSAGE_TYPE = {
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4,
};
我发现最好的方法是将所有枚举值作为数组,并使用indexOf。但是结果代码不是很清楚:
The best way I found is by getting all Enum Values as an array and using indexOf on it. But the resulting code isn't very legible:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}
Is there a simpler way of doing this?
推荐答案
如果您使用的是TypeScript,您可以使用实际枚举。然后,您可以使用中的来检查:
If you are using TypeScript, you can use an actual enum. Then you can check it using in
:
export enum MESSAGE_TYPE {
INFO = 1,
SUCCESS = 2,
WARNING = 3,
ERROR = 4,
};
var type = 3;
if (type in MESSAGE_TYPE) {
}
这样做是因为当您编译上述枚举时,它会生成以下对象:
This works because when you compile the above enum, it generates the below object:
{
'1': 'INFO',
'2': 'SUCCESS',
'3': 'WARNING',
'4': 'ERROR',
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4
}
这篇关于检查TypeScript中的枚举值是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文