Javascript 检查 TypeScript 中的枚举中是否存在值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43804805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if value exists in enum in TypeScript
提问by Tim Schoch
I recieve a number type = 3and have to check if it exists in this enum:
我收到一个数字type = 3,必须检查它是否存在于这个枚举中:
export const MESSAGE_TYPE = {
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4,
};
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:
我发现的最好方法是将所有 Enum 值作为数组获取并在其上使用 indexOf。但是生成的代码不是很清晰:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}
Is there a simpler way of doing this?
有没有更简单的方法来做到这一点?
回答by Xiv
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:
如果您希望它与字符串枚举一起使用,则需要使用,Object.values(ENUM).includes(ENUM.value)因为根据https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html,字符串枚举不是反向映射的:
Enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
becomes:
变成:
{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}
So you just need to do:
所以你只需要做:
if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}
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:
如果您收到以下错误:Property 'values' does not exist on type 'ObjectConstructor',那么您的目标不是 ES2017。您可以使用此 tsconfig.json 配置:
"compilerOptions": {
"lib": ["es2017"]
}
Or you can just do an any cast:
或者你可以做任何演员:
if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}
回答by Saravana
If you are using TypeScript, you can use an actual enum. Then you can check it using in.
如果您使用的是 TypeScript,则可以使用实际的 enum。然后您可以使用in.
This works only if your enum is number-based and notmarked const:
仅当您的枚举基于数字且未标记时才有效const:
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
}
回答by Jayson S.A.
TypeScript v3.7.3
打字稿 v3.7.3
export enum YourEnum {
enum1 = 'enum1',
enum2 = 'enum2',
enum3 = 'enum3',
}
const status = 'enumnumnum';
if (!(status in YourEnum)) {
throw new UnprocessableEntityResponse('Invalid enum val');
}
回答by Ester Kaufman
There is a very simple and easy solution to your question:
您的问题有一个非常简单易行的解决方案:
var districtId = 210;
if (DistrictsEnum[districtId] != null) {
// Returns 'undefined' if the districtId not exists in the DistrictsEnum
model.handlingDistrictId = districtId;
}
回答by Nhan Cao
export enum UserLevel {
Staff = 0,
Leader,
Manager,
}
export enum Gender {
None = "none",
Male = "male",
Female = "female",
}
Difference result in log:
日志中的差异结果:
log(Object.keys(Gender))
=>
[ 'None', 'Male', 'Female' ]
log(Object.keys(UserLevel))
=>
[ '0', '1', '2', 'Staff', 'Leader', 'Manager' ]
The solution, we need to remove key as a number.
解决方案,我们需要将键作为数字删除。
export class Util {
static existValueInEnum(type: any, value: any): boolean {
return Object.keys(type).filter(k => isNaN(Number(k))).filter(k => type[k] === value).length > 0;
}
}
Usage
用法
// For string value
if (!Util.existValueInEnum(Gender, "XYZ")) {
//todo
}
//For number value, remember cast to Number using Number(val)
if (!Util.existValueInEnum(UserLevel, 0)) {
//todo
}

