How to check if value exists in enum in TypeScript?
You can check if a value exists in an enum by comparing it against the enum’s members. The exact technique depends on whether it’s a numeric or string enum.
1. String Enums
For a string enum, you don’t get a reverse mapping automatically. The simplest way is to see if the value is in Object.values(...)
of that enum:
enum Fruit { Apple = "APPLE", Banana = "BANANA", Cherry = "CHERRY" } function isFruit(value: string): value is Fruit { return Object.values(Fruit).includes(value as Fruit); } // Usage console.log(isFruit("BANANA")); // true console.log(isFruit("PINEAPPLE")); // false
Explanation:
Object.values(Fruit)
is["APPLE", "BANANA", "CHERRY"]
.- If
value
is one of these strings, then it exists in the enum.
2. Numeric Enums
With a numeric enum, TypeScript emits a reverse mapping, so you can do:
enum Color { Red, Green, Blue } function isColor(value: number): value is Color { return (Color as any)[value] !== undefined; } console.log(isColor(1)); // true (Green) console.log(isColor(10)); // false
Alternatively:
function isColorByName(value: string): value is keyof typeof Color { return value in Color; } console.log(isColorByName("Green")); // true console.log(isColorByName("Purple")); // false
- For numeric enums,
Color
ends up having both numeric and string keys like{ "0": "Red", "1": "Green", "2": "Blue", Red: 0, Green: 1, Blue: 2 }
.
3. Summary
- String enum:
Object.values(MyEnum).includes(value as MyEnum)
. - Numeric enum: Check reverse mapping or see if key is in
Color
. - This ensures you handle enum membership correctly at runtime.
Also, if you’d like to strengthen your JavaScript (and by extension TypeScript) knowledge, consider the Grokking JavaScript Fundamentals course by DesignGurus.io, which covers foundational JS concepts like prototypes, closures, and async patterns—helping you work more effectively with enums and advanced TypeScript features.
CONTRIBUTOR
TechGrind