Problem
I’ve received a number with type = 3 and need to see if it’s in this enum:
export const MESSAGE_TYPE = {
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4,
};
The easiest solution I’ve discovered is to create an array of all Enum Values and use indexOf on it. However, the resulting code is difficult to read:
if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) {
// do stuff ...
}
Is there a more straightforward approach?
Asked by Tim Schoch
Solution #1
You must use Object.values if you want this to work with string enums (ENUM). According to https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-4.html, string enums are not reverse mapped: includes(ENUM.value).
Enum Vehicle {
Car = 'car',
Bike = 'bike',
Truck = 'truck'
}
becomes:
{
Car: 'car',
Bike: 'bike',
Truck: 'truck'
}
So here’s what you 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 use the following tsconfig.json configuration:
"compilerOptions": {
"lib": ["es2017"]
}
You can also just do any cast:
if ((<any>Object).values(Vehicle).includes('car')) {
// Do stuff here
}
Answered by Xiv
Solution #2
Only non-const, number-based enums are supported. See this answer about const enums and other sorts of enums.
If you are using TypeScript, you can use an actual enum. Then you can use in to check it.
export enum MESSAGE_TYPE {
INFO = 1,
SUCCESS = 2,
WARNING = 3,
ERROR = 4,
};
var type = 3;
if (type in MESSAGE_TYPE) {
}
This works because the above enum yields the following object when it is compiled:
{
'1': 'INFO',
'2': 'SUCCESS',
'3': 'WARNING',
'4': 'ERROR',
INFO: 1,
SUCCESS: 2,
WARNING: 3,
ERROR: 4
}
Answered by Saravana
Solution #3
The easiest way to do this, according to sandersn, is to:
Object.values(MESSAGE_TYPE).includes(type as MESSAGE_TYPE)
Answered by vinczemarton
Solution #4
export enum YourEnum {
enum1 = 'enum1',
enum2 = 'enum2',
enum3 = 'enum3',
}
const status = 'enumnumnum';
if (!Object.values(YourEnum)?.includes(status)) {
throw new UnprocessableEntityResponse('Invalid enum val');
}
Answered by Jayson San Agustin
Solution #5
Your inquiry has a very simple and straightforward answer:
var districtId = 210;
if (DistrictsEnum[districtId] != null) {
// Returns 'undefined' if the districtId not exists in the DistrictsEnum
model.handlingDistrictId = districtId;
}
Answered by Ester Kaufman
Post is based on https://stackoverflow.com/questions/43804805/check-if-value-exists-in-enum-in-typescript