— TypeScript, Enums, Programming — 1 min read
TypeScript enums are a powerful way to organize a set of related values under a single umbrella. Sometimes, you may need to access the names of these enum entries. This article will guide you on how to achieve that.
Enums in TypeScript allow for defining a set of named constants, either numeric or string-based.
1enum Colors {2 Red,3 Green,4 Blue5}
In this enum, Colors
has three members: Red
, Green
, and Blue
.
To get the names of the enum entries, you can iterate over the enum object.
1for (let color in Colors) {2 console.log(color);3}
This will output all the members of the enum, including both names and values.
To filter out the numeric values and only get the names, you can modify the loop as follows:
1for (let color in Colors) {2 if (isNaN(Number(color))) {3 console.log(color);4 }5}
This loop checks if the color
is not a number before printing, effectively filtering out the numeric values.
Retrieving the names of enum entries in TypeScript is a straightforward process. By iterating over the enum and filtering out numeric values, you can easily access the names of the enum members. This technique is useful in various scenarios, such as dynamically populating UI elements or performing validations.