patternjavascriptCritical
Check if value exists in enum in TypeScript
Viewed 0 times
typescriptenumcheckexistsvalue
Problem
I receive a number
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:
Is there a simpler way of doing this?
type = 3 and have to check if it exists in this enum: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:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}Is there a simpler way of doing this?
Solution
If you want this to work with string enums, you need to use
becomes:
So you just need to do:
If you get an error for:
Or you can just do an any cast:
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#string-enums: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 ((Object).values(Vehicle).includes('car')) {
// Do stuff here
}Code Snippets
enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}if (Object.values(Vehicle).includes('car')) {
// Do stuff here
}"compilerOptions": {
"lib": ["es2017"]
}if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}Context
Stack Overflow Q#43804805, score: 697
Revisions (0)
No revisions yet.