How to get names of enum entries?


How to Get Names of Enum Entries?
Have you ever found yourself scratching your head, trying to figure out how to get the names of entries in an enum? You're not alone! Many developers struggle with this common issue when working with enums in TypeScript. 🤔
Let's say you have a TypeScript enum like this:
enum myEnum { entry1, entry2 }
And you want to iterate over the enum and get the names of each enumerated symbol. How do you do it? 🤷♂️
The Problem
The first thing you might try is using a for...in
loop, like this:
for (var entry in myEnum) {
// use entry's name here, e.g., "entry1"
}
But wait! When you try that, you quickly realize that it also includes the numeric keys (indices) of the enum, in addition to the desired symbol names. This can be confusing and not what you were expecting. 😫
So, what's the solution? Let's explore some easy ways to get the names of enum entries.
Solutions
1. Enum keys and values approach
One straightforward solution is to use the Object.keys()
method and filter out the numeric keys. Here's how you can do it:
const enumKeys = Object.keys(myEnum).filter(key => isNaN(Number(key)));
for (let key of enumKeys) {
console.log(key); // output: "entry1", "entry2"
}
By using Object.keys()
, we obtain an array of all the keys (including both the enum names and numeric keys). We then use filter()
to exclude any keys that can be converted to numbers (isNaN(Number(key))
), which effectively removes the numeric keys. Finally, we can iterate over the filtered keys to get the desired enum entry names.
2. Enum values-only approach
Another solution is to extract only the values (symbols) from the enum object and convert them into an array. Here's how you can achieve that:
const enumValues = Object.values(myEnum);
for (let value of enumValues) {
console.log(myEnum[value]); // output: "entry1", "entry2"
}
By using Object.values()
, we directly obtain an array of values (symbols) from the enum object. We can then access the corresponding enum entry names using myEnum[value]
.
Take Action
Now that you know how to get the names of enum entries in TypeScript, go ahead and give it a try! Experiment with these solutions and see which one works best for your specific use case. 🚀
If you found this guide helpful, don't forget to share it with your fellow developers who might be facing the same issue. And if you have any suggestions or alternative approaches, we'd love to hear from you in the comments section below! Let's learn and grow together. 😊
Take Your Tech Career to the Next Level
Our application tracking tool helps you manage your job search effectively. Stay organized, track your progress, and land your dream tech job faster.
