Open In App

How to Get Names of Enum Entries in TypeScript?

A TypeScript enum is a unique class that represents a collection of constants. In this article, we will learn how we can get the names of the entries of a TypeScript enum.

There are many different ways of getting the names of enum entries as listed below:

By using the Object.keys() and Object.values()

We can use the Object.keys() method to get the names of each key of the enum and the Object.values() method to get all the values in the form of an array.

Example: The below example will illustrate the use of the above method to get the names of enum entries in the form of an array.

enum Cricketer {
    Sachin,
    Virat,
    Rohit,
    Dhoni,
    Jadeja
}

const namesArray = Object.keys(Cricketer);
console.log(namesArray);

const valuesArray = Object.values(Cricketer);
console.log(valuesArray);

Output:

[0, 1, 2, 3, 4, Sachin, Virat, Rohit, Dhoni, Jadeja] 
[Sachin, Virat, Rohit, Dhoni, Jadeja, 0, 1, 2, 3, 4]

By using the for-in loop

The for-in loop can also be used to access all the entries of an enum in TypeScript by iterating through each item of the enum.

Example: This example will explain you the use of the for-in loop to get the names of enum entries in TypeScript.

enum Cricketer {
    Sachin,
    Virat,
    Rohit,
    Dhoni,
    Jadeja
}

for (let key in Cricketer) {
    if (!isNaN(Number(key))) {
        continue; 
    }
    console.log("Enum Entry:", key);
}

Output:

Enum Entry: Sachin
Enum Entry: Virat
Enum Entry: Rohit
Enum Entry: Dhoni
Enum Entry: Jadeja

By using the square bracket syntax

We can use the square brackets to get the enum entries in the same way we use tom access the array items.

Example: The below example will explain the use of square brackets syntax to get the enum entries.

enum Cricketer {
    Sachin,
    Virat,
    Rohit,
    Dhoni,
    Jadeja
}

let firstEntry = Cricketer[Cricketer.Sachin];
let firstNumericEntry = Cricketer.Sachin;
console.log("First Entry:", firstEntry);
console.log("First Numeric Entry:", firstNumericEntry);

Output:

First Entry: Sachin
First Numeric Entry: 0 

Using the Object.getOwnPropertyNames()

Another method to retrieve the names of enum entries is by utilizing the Object.getOwnPropertyNames() function. This method returns an array of all properties (including non-enumerable properties except for those which use Symbol) found directly upon a given object.

Example: In this example the enum entries' names using Object.getOwnPropertyNames() and filtering out non-enumerable properties, ensuring only enum entries are included in the result.

enum Cricketer {
    Sachin,
    Virat,
    Rahul,
    Dhoni,
    Jadeja
}

const enumEntries = Object.getOwnPropertyNames(Cricketer).filter(
    prop => isNaN(parseInt(prop)));
console.log(enumEntries);

Output:

[ 'Sachin', 'Virat', 'Rahul', 'Dhoni', 'Jadeja' ]
Article Tags :