Enum reverse mapping surprise
Quick summary
You iterated over a numeric enum and got both keys and values — TypeScript creates reverse mappings for numeric enums.
Why this happens
You used Object.keys() or for...in on a numeric enum, which includes reverse-mapped value-to-key entries
You expected only enum keys but got both keys and numeric values due to reverse mapping
A string enum was changed to numeric, introducing reverse mapping that broke existing iteration code
Minimal example
enum Status { Active, Inactive, Pending }
console.log(Object.keys(Status)); // ['0', '1', '2', 'Active', 'Inactive', 'Pending']
console.log(Object.values(Status)); // [0, 1, 2, 'Active', 'Inactive', 'Pending']const Status = { Active: 'Active', Inactive: 'Inactive', Pending: 'Pending' } as const;
console.log(Object.keys(Status)); // ['Active', 'Inactive', 'Pending']
console.log(Object.values(Status)); // ['Active', 'Inactive', 'Pending']Using a const object instead of a numeric enum eliminates reverse mapping, so iteration only produces the defined keys and values.
How to diagnose
Log Object.keys(Enum) and Object.values(Enum) to see the extra reverse-mapped entries
Check whether the enum is numeric (has reverse mapping) or string-based (does not)
Use a type guard or filter to separate keys from values when iterating a numeric enum
How to fix
Use string enums instead of numeric enums to avoid reverse mapping entirely
Filter the keys to exclude numeric ones when iterating: keys.filter(k => isNaN(Number(k)))
Use a constant object with 'as const' instead of an enum for better control over iteration
How to prevent
Prefer string enums or const objects over numeric enums to avoid reverse mapping surprises
Never iterate over enums directly — use a typed array of known keys or values instead
Related Resources
Related Glossary
Related Lessons
- Enums
Learn about enums.