Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists in enum in TypeScript

I recieve a number 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?

like image 562
Tim Schoch Avatar asked May 05 '17 12:05

Tim Schoch


People also ask

How do you check if a value is present in an enum or not?

Enum. IsDefined is a check used to determine whether the values exist in the enumeration before they are used in your code. This method returns a bool value, where a true indicates that the enumeration value is defined in this enumeration and false indicates that it is not. The Enum .

How do you check if a string is present in an enum Java?

Then you can just do: values. contains("your string") which returns true or false.

What is enum value?

Enum. valueOf() method returns the enum constant of the specified enumtype with the specified name. The name must match exactly an identifier used to declare an enum constant in this type.


1 Answers

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 } 
like image 134
Xiv Avatar answered Sep 20 '22 00:09

Xiv