How to check if value is in enum in TypeScript
October 27, 2023
In TypeScript, enums allow you to define named sets of numeric or string values. Sometimes, you'll want to determine if a specific value exists within an enum. Here's how to do that efficiently.
Before diving into checking values, it's important to understand the structure of enums. In TypeScript, an enum can be numeric or string-based.
Checking if a numeric value is in an enum
To verify if a numeric value is part of an enum, you can use the
in keyword, combined with the enum's name.
Checking if a string value is in an enum
For string-based enums, you can still use the
in keyword. But, to ensure that you're only checking against the enum's actual values (and not its reverse mapping), you'll need to utilize the
Guarding against reverse mapping
TypeScript provides reverse mapping for numeric enums. This means you can access the name of an enum member given its value. However, this also means you need to be careful when checking if a string is in a numeric enum.
To guard against this, ensure that the value you're checking is not a number.
Using helper functions
For repeated checks, you might consider wrapping the above logic in helper functions.
By following the above approaches, you can confidently check if values exist within your TypeScript enums, ensuring cleaner and more maintainable code.
How to fix the "not all code paths return a value" issue in TypeScript
Working with WebSockets in Node.js using TypeScript
Type Annotations Can Only Be Used in TypeScript Files
Guide to TypeScript Recursive Type
How to Configure Knex.js with TypeScript