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]
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()