How to get names of enum entries?
In TypeScript, you can get the names of an enum’s entries by examining the keys of the enum object at runtime. However, numeric enums and string enums behave slightly differently. Below are common approaches.
1. Numeric Enums (with Reverse Mappings)
When you have a numeric enum, TypeScript generates both forward and reverse mappings. For example:
enum Color { Red, Green, Blue } // This compiles down to an object like: // { // 0: "Red", // 1: "Green", // 2: "Blue", // Red: 0, // Green: 1, // Blue: 2 // } const keys = Object.keys(Color); // ["0", "1", "2", "Red", "Green", "Blue"] // If you only want the string names ("Red", "Green", "Blue"): const enumNames = keys.filter(key => isNaN(Number(key))); console.log(enumNames); // ["Red", "Green", "Blue"]
Explanation:
Object.keys(Color)
returns all keys, including numeric and string-based reverse mappings.filter(key => isNaN(Number(key)))
excludes the numeric keys ("0","1","2"), leaving only the enum’s string names.
2. String Enums (No Reverse Mappings)
For string enums:
enum Fruit { Apple = "APPLE", Banana = "BANANA", Cherry = "CHERRY" } // This compiles to an object like: // { Apple: "APPLE", Banana: "BANANA", Cherry: "CHERRY" } const keys = Object.keys(Fruit); // ["Apple","Banana","Cherry"] console.log(keys); // direct result
- There’s no numeric reverse mapping for string enums, so
Object.keys()
only includes the “forward” property names. - The values are
"APPLE","BANANA","CHERRY"
, etc.
If you wanted the string literal values themselves, you could do:
const values = Object.keys(Fruit).map(key => Fruit[key as keyof typeof Fruit]); console.log(values); // ["APPLE", "BANANA", "CHERRY"]
3. Summarizing Patterns
- Numeric enums generate both numeric and string keys. Filter out numeric keys to get the names of the enum members.
- String enums have only the string keys, so
Object.keys()
directly returns the enum member names. If you need the string values (the assigned constants), you map back through the enum.
If you want to deepen your knowledge of core JavaScript (which underpins TypeScript and its runtime behavior), check out the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers essential topics like closures, prototypes, and async patterns, helping you better understand how TypeScript translates to JS and how these enumerations behave at runtime.