How to Convert an Enum to an Array in TypeScript?

As a developer working on a project for a US-based company, I recently faced a situation where I needed to transform a TypeScript enum into an array of objects. In this tutorial, I will explain how to convert an enum to an array in TypeScript.

Understanding TypeScript Enums

Before we dive into converting an enum to an array, let’s briefly discuss what enums are in TypeScript. An enum, short for enumeration, is a way to define a set of named constants. It allows you to create a group of related values that can be referred to by their names, making the code more readable and maintainable.

Here’s an example of a TypeScript enum representing the states in the USA:

enum USState {
  California = 'CA',
  Texas = 'TX',
  Florida = 'FL',
  NewYork = 'NY',
  // ...
}

In this example, we define an enum called USState with four named constants representing different states in the USA.

Check out TypeScript Array of Arrays

Convert an Enum to an Array in TypeScript

Now, let’s explore different approaches to convert an enum to an array in TypeScript.

Approach 1: Using Object.values()

One of the simplest ways to convert an enum to an array in TypeScript is by using the Object.values() method. This method returns an array of a given object’s own enumerable property values.

Here’s an example:

enum USState {
  California = 'CA',
  Texas = 'TX',
  Florida = 'FL',
  NewYork = 'NY',
}

const stateArray = Object.values(USState);
console.log(stateArray);
// Output: ['CA', 'TX', 'FL', 'NY']

In this approach, we use Object.values(USState) to get an array of the enum values. The resulting stateArray contains the string values of the enum constants.

Here is the exact output in the screenshot below:

Convert an Enum to an Array in TypeScript

Read How to Use TypeScript For Loops with Arrays?

Approach 2: Using Object.keys() and Map

Another approach is to use the Object.keys() method in combination with the map() function to create an array of objects containing both the enum keys and values.

Here’s an example and the complete TypeScript code.

enum USState {
  California = 'CA',
  Texas = 'TX',
  Florida = 'FL',
  NewYork = 'NY',
}

const stateArray = Object.keys(USState).map(key => ({
  key,
  value: USState[key as keyof typeof USState]
}));

console.log(stateArray);
/* Output:
[
  { key: 'California', value: 'CA' },
  { key: 'Texas', value: 'TX' },
  { key: 'Florida', value: 'FL' },
  { key: 'NewYork', value: 'NY' }
]
*/

In this approach, we use Object.keys(USState) to get an array of the enum keys. Then, we use the map() function to transform each key into an object that contains both the key and its corresponding value from the enum.

The resulting stateArray is an array of objects, where each object has a key property representing the enum constant name and a value property representing its value.

Here is the exact output in the screenshot below:

Typescript Convert an Enum to an Array

Read How to Use Join() Method to Combine Array of Strings in TypeScript?

Approach 3: Using a Custom Utility Function

For a more reusable and type-safe approach, you can create a custom utility function to convert an enum to an array in TypeScript. This function can be generic, allowing it to work with any enum type.

Here’s an example of a custom utility function:

function enumToArray<T extends object>(enumObj: T): { key: keyof T, value: T[keyof T] }[] {
  return Object.keys(enumObj).map(key => ({
    key: key as keyof T,
    value: enumObj[key as keyof T]
  }));
}

enum USState {
  California = 'CA',
  Texas = 'TX',
  Florida = 'FL',
  NewYork = 'NY',
}

const stateArray = enumToArray(USState);
console.log(stateArray);

In this approach, we define a generic function called enumToArray that takes an enum object as a parameter. The function uses Object.keys() and map() to create an array of objects containing the enum keys and values, similar to the previous approach. The resulting array is type-safe and can be used with any enum type.

Here is the exact output in the screenshot below:

How to Convert an Enum to an Array in TypeScript

Read How to Use Array Reduce() Method in TypeScript?

Convert an Enum to an Array in TypeScript Example

Consider a real-world scenario where converting an enum to an array can be helpful. Suppose you’re building a web application allowing users to select their state during checkout. You have an enum representing the US states, and you need to populate a dropdown menu with these states.

Here’s an example of how you can use the enumToArray utility function to achieve this:

enum USState {
  California = 'CA',
  Texas = 'TX',
  Florida = 'FL',
  NewYork = 'NY',
  // ...
}

// Convert the USState enum to an array
const stateOptions = enumToArray(USState);

// Populate the dropdown menu with the state options
const stateDropdown = document.getElementById('stateDropdown') as HTMLSelectElement;
stateOptions.forEach(option => {
  const optionElement = document.createElement('option');
  optionElement.value = option.value;
  optionElement.text = option.key;
  stateDropdown.add(optionElement);
});

In this example, we use the enumToArray function to convert the USState enum to an array of objects. We then retrieve the dropdown menu element from the HTML using its ID ('stateDropdown').

Finally, we iterate over the stateOptions array and create an <option> element for each state, setting its value and text properties accordingly. The dropdown menu will now be populated with the US states, allowing users to select their state during the checkout process.

Conclusion

In this tutorial, I explained how to convert an enum to an array in Typescript using different methods, such as using Object.values(), Object.keys() with map(), or a custom utility function, etc. I hope the above examples will help you.