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.

Javascript
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]

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:

Table of Content

  • By using the Object.keys() and Object.values()
  • By using the for-in loop
  • By using the square bracket syntax
  • By Using the Object.getOwnPropertyNames()

Similar Reads

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....

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....

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....

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....