Check if a Value Exists in a TypeScript Enum
TypeScript enums are converted into objects like this:
ts
// Enum
enum Vehicle {
Car = 'car',
Bus = 'bus',
Train = 'train',
Subway = 'subway'
}
// Converted to the following object
{
Car: 'car',
Bus: 'bus',
Train: 'train',
Subway: 'subway'
}
Therefore, we can use Object.values(...)
to check if a value exists in the enum.
ts
const car = Vehicle.Car;
Object.values(Vehicle).includes(car); // true
Object.values(Vehicle).includes('motor'); // false