检查 TypeScript 中的枚举中是否存在值 [英] Check if value exists in enum in 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?
推荐答案
如果你想让它与字符串枚举一起工作,你需要使用 Object.values(ENUM).includes(ENUM.value)
因为字符串枚举没有反向映射,根据 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:
If you want this to work with string enums, you need to use Object.values(ENUM).includes(ENUM.value)
because string enums are not reverse mapped, according to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html:
Enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
变成:
{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}
所以你只需要:
if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}
如果您收到以下错误:Property 'values' does not exist on type 'ObjectConstructor'
,那么您的目标不是 ES2017.您可以使用此 tsconfig.json 配置:
If you get an error for: Property 'values' does not exist on type 'ObjectConstructor'
, then you are not targeting ES2017. You can either use this tsconfig.json config:
"compilerOptions": {
"lib": ["es2017"]
}
或者你可以做任何演员:
Or you can just do an any cast:
if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}
这篇关于检查 TypeScript 中的枚举中是否存在值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!