Check if value exists in enum in TypeScript
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'
}
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:
"compilerOptions": {
"lib": ["es2017"]
}
Or you can just do an any cast:
if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}
According to sandersn the best way to do this would be:
Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)
This works only on non-const, number-based enums. For const enums or enums of other types, see this answer
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
}