How to use the Object.getOwnPropertyNames() In Typescript
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' ]
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()