Check if value exists in enum in TypeScript
Quickly determine if an enum in TypeScript contains a value by using the in
operator for keys or Object.values()
for values.
Check out this concise example:
Here, isKey
determines if the enum key exists, while isValue
verifies the existence of a value within the enum.
Enum types and value checks
Enums in TypeScript can be diverse, requiring different approaches for value existence checks. Let's go over the most common types: string and number-based enums.
Checking values in string enums
For string enums, Object.values()
is your best mate:
But stay alert! If your ECMAScript version isn't correctly set, you may encounter some errors. Don't sweat it, though. Just update your tsconfig.json
:
Occasionally, TypeScript may grumble about unexpected types. To hush it, use an explicit cast:
Checking values in number-based enums
With number-based enums, it's a little different game:
To verify a value, use the bracket notation based on enum's property lookup:
Extra points: advanced checking techniques
What if basic usage doesn't cut it? Advanced tactics to the rescue!
Taming diverse enum values with casting
When your enum values are a motley crew of types, type assertion is a game changer:
Enum iteration for expanded verification
When faced with complex checks or runtime enums, iteration is worth its weight in gold:
Beware the enum quirks
Enums can be a little sneaky:
- Using
const enums
is tricky since they get inlined at compile time. - Runtime type checks might need manual iteration due to TypeScript transpiling.
- TypeScript doesn't do reverse mapping for string enums like it kindly does for number enums.
Enums on hard mode: special cases
Sometimes enums play hardball. Here are some expert techniques:
Tackling mixed type enums
If you're dealing with a complex enum, juggle your checks:
Type narrowing for enums
User-defined type guards come in handy when using enums:
Was this article helpful?