How can I get the names of enum entries in TypeScript?

How can I get the names of enum entries in TypeScript?

I would like to iterate over a TypeScript enum object and get each enumerated symbol name. For example, with the enum enum myEnum { entry1, entry2 },

I want to access each entry’s name, such as "entry1". How can I achieve this using the typescript enum to string method?

To handle such entires in TypeScript you can try what worked for me.

Iterating Over the Enum with Object.keys() You can use Object.keys() to retrieve the names of the enum entries as strings.

enum myEnum { entry1, entry2 }

for (let entry of Object.keys(myEnum)) {
    if (isNaN(Number(entry))) {  // To filter out numeric keys
        console.log(entry); // Output: "entry1", "entry2"
    }
}

This method treats the enum as an object and uses Object.keys() to iterate through the names of the enum entries.

Hey

Great solution by @charity-majors , just want to share my solution

I used Object.getOwnPropertyNames() Another method is to use Object.getOwnPropertyNames(), which retrieves both string and numeric keys of the enum.

enum myEnum { entry1, entry2 }

for (let entry of Object.getOwnPropertyNames(myEnum)) {
    if (isNaN(Number(entry))) {  // Filter out numeric values
        console.log(entry); // Output: "entry1", "entry2"
    }
}

This solution is similar to the previous one but ensures that you get all the property names, including non-enumerable ones.

TypeScript creates a reverse mapping for numeric enums, so you can also access the string names using the reverse mapping. enum myEnum { entry1, entry2 }

for (let entry in myEnum) {
    if (isNaN(Number(entry))) {
        console.log(entry); // Output: "entry1", "entry2"
    }
}

This approach works because the enum has both numeric and string keys, and filtering out numeric ones ensures you only get the names of the entries.