DEV Community

Discussion on: TypeScript's enum + JavaScript's "in" = 👍

Collapse
 
ignusg profile image
Jonathan • Edited

Don't do this. It produces wrong results since it relies on the enum's internal value which is just a number - it matches wrong enum values to each other:

enum Type {
Disabled, // This is 1
Enabled, // This is 2
Pending, // This is 3
}

enum AllowedTypes {
Enabled, // This is 1
Pending, // This is 2
}

const state = Type.Enabled;

console.log(Type.Pending in AllowedTypes); // This checks if 3 is in { 1: 'Enabled', 2: 'Pending' } which is why it returns false

PS: You "could" technically make this work with string enums but you would have to make sure the value you assign matches the key and there are no duplicates (this is not checked by TS)

Collapse
 
andrewmcoupe profile image
Andy Coupe • Edited

Ah yes, good spot! I had a check and the status is received as a string value from our database so in my case it works well.