How do you create a type-safe iteration over all values of a string enum?
Short answer
Use Object.values(EnumName) to get an array of the enum's values (safe for string enums, since they don't generate reverse-mapping numeric keys), optionally typed explicitly as an array of the enum type for full type safety when iterating.
Advertisement
AModel answer
Use Object.values(EnumName) to get an array of the enum's values (safe for string enums, since they don't generate reverse-mapping numeric keys), optionally typed explicitly as an array of the enum type for full type safety when iterating.
enum Status { Active = 'ACTIVE', Inactive = 'INACTIVE' }
const allStatuses = Object.values(Status) as Status[];
allStatuses.forEach(s => console.log(s)); // 'ACTIVE', 'INACTIVE'Real-world example
Populating a dropdown's options dynamically from every possible enum value, without hardcoding the list separately.
Likely follow-ups
- Why does the same Object.values() approach behave differently (and need filtering) for numeric enums?
Related topics