How to Get Names of Enum Entries in TypeScript

To get the names of enum entries in TypeScript, you can use the Object.keys() function.

Example

Define an enum.

enum MyEnum {
  ValueA = "VALUE_A",
  ValueB = "VALUE_B",
  ValueC = "VALUE_C",
}

Get the names of Enum entries using the Object.keys() function.

enum MyEnum {
  KEY_A = "VALUE_A",
  KEY_B = "VALUE_B",
  KEY_C = "VALUE_C",
}

const enumNames = Object.keys(MyEnum);

console.log(enumNames);

Output

[ 'KEY_A', 'KEY_B', 'KEY_C' ]

In this example, the Object.keys(MyEnum) function returns an array of the Enum’s entry names.

Remember that it works for both string-based Enums and numeric Enums. If you have a numeric Enum and want to get the names of the entries, you can use the same approach:

enum NumericEnum {
  ValueA,
  ValueB,
  ValueC,
}
 
 const numericEnumNames = Object.keys(NumericEnum).filter(
   (key) => isNaN(Number(key))
 );
 
 console.log(numericEnumNames);

Output

[ 'ValueA', 'ValueB', 'ValueC' ]

For numeric Enums, you need to filter out the numeric keys to get only the names of the Enum entries.

The isNaN(Number(key)) check helps to filter out numeric keys, leaving only the names.

That’s it.

Leave a Comment