How to Convert TypeScript Enum to Array

Here are two main ways to convert an Enum to an Array in TypeScript.

  1. Using the Object.keys() method
  2. Using the Object.values() method

Enums in TypeScript, unlike interfaces, exist at runtime. They are converted into real objects by the TypeScript compiler.

Converting a Numeric Enum into an Array

To convert a numeric enum into an array, you can use the “Object.values()” method.

enum Days {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

console.log(Object.values(Days));

Output

Converting a Numeric Enum into an Array

Converting an Enums key-value pair to an array

To convert TypeScript enum. to an array of key-value pairs, you can use the “Object.entries()” method along with the “filter()” method that removes any pairs where the value isn’t a number.

enum Days {
  Sunday,
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday
}

const enumPairs: [string, number][] = Object.entries(Days)
  .filter(([key, value]) => typeof value === 'number')
  .map(([key, value]) => [key, value as number]);

console.log(enumPairs);

Output

Converting an Enums key-value pair to an array

Converting a string enum into an array

Here are three ways to convert a string enum to an array in TypeScript.

  1. Array of Enum’s Keys
  2. Array of Enum’s Values
  3. Array of Enum’s Key-Value Pairs

Array of Enum’s Keys

enum Colors {
 Red = "RED",
 Green = "GREEN",
 Blue = "BLUE"
}

const enumKeys: string[] = Object.keys(Colors);
console.log(enumKeys);

Output

Converting a string enum into an array

Array of Enum’s Values

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

const enumValues: string[] = Object.values(Colors);
console.log(enumValues);

Output

Array of Enum's Values

Array of Enum’s Key-Value Pairs

enum Colors {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

const enumPairs: [string, string][] = Object.entries(Colors);

console.log(enumPairs);

Output

Array of Enum's Key-Value Pairs

That’s it!

Related posts

TypeScript String to Number

TypeScript String to Enum

TypeScript Enum to String

TypeScript String to Boolean

Leave a Comment