Convert TypeScript Enums to Arrays

Do you ever need to change an enum to an array in TypeScript? It is a little tricky, but various methods are available for this.

I will show you various methods to convert TypeScript enums to arrays with examples in this tutorial.

What Are TypeScript Enums?

If you are new to enums in TypeScript, here is a small definition and an example. However, I recommend checking the tutorial I wrote recently on what an enum is in TypeScript.

In TypeScript, an enum (short for enumeration) is a special data type that allows you to define a set of named constants. Enums make it easier to document intent or create a set of distinct cases.

In short, an enum in TypeScript is a way of giving more friendly names to sets of numeric or string values.

For example, here’s a simple enum representing days of the week:

enum DaysOfWeek {
  Monday = 0,
  Tuesday = 1,
  Wednesday = 2,
  Thursday = 3,
  Friday = 4,
  Saturday = 5,
  Sunday = 6
}

Now, let me show how to convert these enums into arrays using four or five different methods.

Method 1: Using Object.keys() for Enum Names

The Object.keys() method is one of the best ways to extract enum keys as an array. This works because TypeScript enums compile down to JavaScript objects at runtime.

Here is an example.

enum Color {
  Red = "#FF0000",
  Green = "#00FF00",
  Blue = "#0000FF"
}

// Get enum keys as array
const colorNames = Object.keys(Color).filter(key => isNaN(Number(key)));
console.log(colorNames); // ["Red", "Green", "Blue"]

Here is how this works:

  1. Object.keys(Color) returns all keys from the Color enum object
  2. We use .filter(key => isNaN(Number(key))) to remove numeric keys
  3. This filtering is necessary because TypeScript generates reverse mappings for numeric enums (where values map back to keys)

For example, if we didn’t filter, we might get: ["Red", "Green", "Blue", "0", "1", "2"] which includes both the names and the numeric indices.

Here is the exact output in the screenshot below;

Convert TypeScript Enums to Arrays

This approach is perfect when you:

  • Only need the names/keys of your enum
  • Want a simple, straightforward solution
  • Need to create string-based selections or labels

For example, if you’re building a color picker component, you might want to list all available color names without their hex values.

Check out Check If a String Is in an Enum in TypeScript

Method 2: Using Object.values() for Enum Values

Now let me show you another method to convert an enum to an array in TypeScript.

While Object.keys() gets you the enum member names, Object.values() retrieves the actual values. This is particularly useful when the values themselves are what you need to work with.

Here is an example.

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

// Get enum values as array
const directionValues = Object.values(Direction);
console.log(directionValues); // ["UP", "DOWN", "LEFT", "RIGHT"]

How this method works:

  1. Object.values(Direction) extracts all values from the Direction enum
  2. For string enums like this example, the values are straightforward strings
  3. For numeric enums, you’d get the numeric values

Here is the exact output in the screenshot below. I have executed the code using an online TypeScript compiler.

Convert Enums to Arrays in TypeScript

It’s important to note that with numeric enums, Object.values() will include both the numeric values and the enum names because of TypeScript’s reverse mapping. You might need additional filtering for those cases:

enum NumericEnum {
  One = 1,
  Two = 2,
  Three = 3
}

// Get only numeric values
const numericValues = Object.values(NumericEnum).filter(value => !isNaN(Number(value)));
console.log(numericValues); // [1, 2, 3]

Native object methods like Object.values() and Object.keys() can be used at runtime to construct arrays from enums efficiently.

Use this approach when:

  • You only care about the values stored in the enum
  • Your enum values are more meaningful than the keys
  • You’re building a system that needs to process the actual values

For example, if your Direction enum represents API parameters for a navigation system, you’d want the actual string values (“UP”, “DOWN”, etc.) to send in requests.

Read TypeScript Enum Naming Conventions

Method 3: Creating an Array of Key-Value Pairs with Object.entries()

Sometimes, you need both the keys and values from an enum, especially when building more complex data structures. The Object.entries() method gives you both in a convenient format.

enum UserRole {
  Admin = "ADMIN",
  Editor = "EDITOR",
  Viewer = "VIEWER"
}

// Convert to array of objects with id and name
const roleArray = Object.entries(UserRole).map(([key, value]) => ({
  id: value,
  name: key
}));

console.log(roleArray);
/* Output:
[
  { id: "ADMIN", name: "Admin" },
  { id: "EDITOR", name: "Editor" },
  { id: "VIEWER", name: "Viewer" }
]
*/

Let’s break down this approach:

  1. Object.entries(UserRole) returns an array of [key, value] pairs
  2. We use .map() to transform each pair into a custom object format
  3. Each resulting object has an id property (the enum value) and a name property (the enum key)

For numeric enums, you’d again need to handle reverse mappings:

enum Status {
  Active = 1,
  Pending = 2,
  Inactive = 3
}

const statusArray = Object.entries(Status)
  .filter(([key]) => isNaN(Number(key)))
  .map(([key, value]) => ({
    id: Number(value),
    name: key
  }));

console.log(statusArray);
/* Output:
[
  { id: 1, name: "Active" },
  { id: 2, name: "Pending" },
  { id: 3, name: "Inactive" }
]
*/

This method uses map() to convert the data to the desired format, with ID obtained from the enum value and name from the key.

Use this method when:

  • You need both keys and values in a structured format
  • You’re building UI components like dropdowns or selection lists
  • You want to transform data for API requests or responses

For instance, when creating a role selection dropdown, you’d want both the human-readable role name and the corresponding role ID value to send to your backend.

Check out Convert String to Enum in TypeScript

Method 4: Using a Generic Utility Function

To avoid repeating conversion code throughout your application, you can create a reusable utility function that works with any enum type:

function enumToArray<T extends object>(enumObject: T): Array<{ key: string; value: string | number }> {
  return Object.keys(enumObject)
    .filter(key => isNaN(Number(key)))
    .map(key => ({
      key,
      value: enumObject[key as keyof T]
    }));
}

// Usage example
enum PaymentStatus {
  Pending = "PENDING",
  Completed = "COMPLETED",
  Failed = "FAILED",
  Refunded = "REFUNDED"
}

const paymentStatusArray = enumToArray(PaymentStatus);
console.log(paymentStatusArray);
/* Output:
[
  { key: "Pending", value: "PENDING" },
  { key: "Completed", value: "COMPLETED" },
  { key: "Failed", value: "FAILED" },
  { key: "Refunded", value: "REFUNDED" }
]
*/

Here’s what makes this function powerful:

  1. It’s generic, accepting any object type T (including enums)
  2. It handles the filtering of numeric keys automatically
  3. It produces a consistent output format with both keys and values
  4. It provides type safety through TypeScript generics

You can easily customize this function to return different formats based on your needs:

// Version that returns arrays with custom property names
function enumToCustomArray<T extends object, K extends string, V extends string>(
  enumObject: T, 
  keyProp: K, 
  valueProp: V
): Array<Record<K, string> & Record<V, string | number>> {
  return Object.keys(enumObject)
    .filter(key => isNaN(Number(key)))
    .map(key => ({
      [keyProp]: key,
      [valueProp]: enumObject[key as keyof T]
    }) as Record<K, string> & Record<V, string | number>);
}

// Usage with custom property names
const paymentOptions = enumToCustomArray(PaymentStatus, 'label', 'code');
console.log(paymentOptions);
/* Output:
[
  { label: "Pending", code: "PENDING" },
  { label: "Completed", code: "COMPLETED" },
  { label: "Failed", code: "FAILED" },
  { label: "Refunded", code: "REFUNDED" }
]
*/

This approach can be used to dynamically convert the enum to an array format, handling different enum types.

This utility function is ideal when:

  • You need to convert multiple enums in your application
  • You want consistency in how enums are transformed
  • You’re building a library or shared utility
  • You need different output formats depending on the context

This approach follows the DRY (Don’t Repeat Yourself) principle, centralizing the conversion logic in one place.

Check out How to Iterate Over Enums in TypeScript?

Method 5: Creating Typed Arrays for Strict Type Safety

For maximum type safety and better developer experience, you can create strongly-typed arrays that maintain the enum’s type information:

enum State {
  California = "CA",
  Texas = "TX",
  NewYork = "NY",
  Florida = "FL"
}

// Get a typed array of enum values
type StateCode = `${State}`;
const stateCodes: StateCode[] = Object.values(State) as StateCode[];

// Get a typed array of enum keys
type StateName = keyof typeof State;
const stateNames: StateName[] = Object.keys(State) as StateName[];

console.log(stateCodes); // ["CA", "TX", "NY", "FL"]
console.log(stateNames); // ["California", "Texas", "NewYork", "Florida"]

This method leverages TypeScript’s advanced type system:

  1. typeof State gets the type of the enum object itself
  2. keyof typeof State creates a union type of all valid enum key strings
  3. ${State} creates a template literal type with all possible enum values
  4. The as casting ensures TypeScript recognizes the arrays with the correct types

The major benefit here is that TypeScript will provide autocomplete and type checking for these arrays:

function isValidState(state: StateName): boolean {
  return stateNames.includes(state); // TypeScript knows exactly what's valid
}

// TypeScript knows this is valid
isValidState("California"); // true

// TypeScript will show an error at compile time
isValidState("Arizona"); // Error: Argument of type '"Arizona"' is not assignable to parameter of type 'StateName'

This type of approach allows you to create a type that is an array with elements for each enum member, providing stronger type checking.

Use this approach when:

  • You need strict type safety in your TypeScript code
  • You’re working in a large team where type consistency is crucial
  • You want to leverage TypeScript’s type system for better IntelliSense
  • You’re building applications that benefit from early error detection
  • You need to ensure only valid enum values are used throughout your codebase

The typed arrays approach might seem more complex at first, but it pays dividends in larger projects by catching potential bugs during development rather than at runtime.

Check out TypeScript Enum Reverse Mapping

Comparison of Methods

Let’s compare these different approaches with a detailed analysis so you can decide when to use which method.

MethodProsConsBest For
Object.keys()– Simple and straightforward
– Minimal code required
– Easy for beginners to understand
– Only gives keys/names
– Requires filtering for numeric enums
– No type safety guarantees
– Basic use cases
– When you only need enum names
– Quick prototyping
Object.values()– Direct access to enum values
– Works well with string enums
– Straightforward implementation
– Only gives values, no context of keys
– Needs handling for numeric enums
– Less type information preserved
– When values are the focus
– API parameter generation
– Data validation
Object.entries()– Provides both keys and values
– Flexible transformation options
– Preserves relationship between keys/values
– More verbose
– Requires more processing
– May need custom mapping
– Complex UI components
– Rich data needs
– When context is important
Generic Utility– Reusable across your application
– Consistent output format
– Customizable to different needs
– DRY principle
– Slightly more complex to set up
– May be overkill for simple cases
– Requires understanding of generics
– Applications with many enums
– Shared libraries
– Projects with consistent data needs
Typed Arrays– Maximum type safety
– Best developer experience
– Early error detection
– IDE autocompletion
– More TypeScript-specific knowledge required
– More complex type definitions
– Might be harder for beginners
– Large teams
– Complex applications
– Enterprise software
– Projects with strict requirements

In this tutorial, I explained how to convert an enum to an array in TypeScript using different methods.

Here is a summary of each method:

  1. Object.keys() – Get enum keys/names as an array
  2. Object.values() – Get enum values as an array
  3. Object.entries() – Convert to an array of key-value pairs
  4. Generic Utility Functions – Create reusable, consistent conversion tools
  5. Typed Arrays – Maintain strict type safety during conversion

You may also like:

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App