Skip to content

Getting Names of Enum Entries in TypeScript

TypeScript, Enums, Programming1 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.

Enum Basics in TypeScript

Enums in TypeScript allow for defining a set of named constants, either numeric or string-based.

Example Enum Definition

1enum Colors {
2 Red,
3 Green,
4 Blue

In this enum, Colors has three members: Red, Green, and Blue.

Retrieving Enum Names

Iterating Over Enum

To get the names of the enum entries, you can iterate over the enum object.

1for (let color in Colors) {
2 console.log(color);

This will output all the members of the enum, including both names and values.

Filtering Enum Names

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 }

This loop checks if the color is not a number before printing, effectively filtering out the numeric values.

In Closing

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.