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.

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

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