Check if value in enum in TypeScript exists

I get the number type = 3 and should check if it exists in this enumeration:

 export const MESSAGE_TYPE = { INFO: 1, SUCCESS: 2, WARNING: 3, ERROR: 4, }; 

The best way I've found is to get all Enum values ​​as an array and use indexOf. But the resulting code is not very readable:

 if( -1 < _.values( MESSAGE_TYPE ).indexOf( _.toInteger( type ) ) ) { // do stuff ... } 

Is there an easier way to do this?

+16
source share
2 answers

If you want this to work with line enums, you need to use Object.values(ENUM).includes(ENUM.value) because line enums are not displayed backwards, 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(Vehicle.car) { // Do stuff here } 
+13
source

If you use TypeScript, you can use the actual enumeration . 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 listing, it generates the following object:

 { '1': 'INFO', '2': 'SUCCESS', '3': 'WARNING', '4': 'ERROR', INFO: 1, SUCCESS: 2, WARNING: 3, ERROR: 4 } 
+28
source

Source: https://habr.com/ru/post/1273043/


All Articles