How to Get All Enum Values in TypeScript

While working on a TypeScript project, I had an enum that listed different user roles, such as Admin, Editor, and Viewer. I wanted to display all these roles in a drop-down menu on the webpage.

To achieve this, I needed a way to retrieve all the values from the enum so I could loop through them and display them in the UI. That’s when I started looking for the best way to get all enum values in TypeScript.

In this tutorial, I will explain how to get all enum values in TypeScript. This can be particularly useful for scenarios where you have a fixed set of related values, such as the states of a process or the categories of a product.

However, there are times when you might need to retrieve all the values of an enum, and this is where things can get a bit tricky. Here, I’ll share my experience and solutions to this common problem.

What are Enums in TypeScript?

Enums in TypeScript are a way to give more friendly names to sets of numeric or string values. They can be used to represent a collection of related values in a more readable and maintainable way. Here’s a basic example:

enum States {
    California,
    Texas,
    Florida,
    NewYork,
}

In this example, States is an enum with four values representing different states in the USA. By default, enums are assigned numeric values starting from 0, so California is assigned the value 0, Texas is assigned the value 1, and so on.

Why Retrieve All Enum Values in TypeScript?

There are several scenarios where you might need to retrieve all the values of an enum:

  1. Form Dropdowns: When you need to populate a dropdown list with all possible values of an enum.
  2. Validation: To validate if a given value is part of the enum.
  3. Logging and Debugging: To log all possible states or categories for debugging purposes.

How to Get All Enum Values in TypeScript

To get all values of an enum, you can use the Object.keys() and Object.values() methods. Here’s how you can do it:

Using Object.keys() and Object.values()

The simplest way to get all values is to use Object.keys() and Object.values(). This method is straightforward and works well for most use cases.

enum States {
    California,
    Texas,
    Florida,
    NewYork,
}

const enumValues = Object.keys(States)
    .filter(key => isNaN(Number(key)))
    .map(key => States[key as keyof typeof States]);

console.log(enumValues); // Output: [ 'California', 'Texas', 'Florida', 'NewYork' ]

In this code snippet:

  • Object.keys(States) returns an array of all keys and values of the enum.
  • filter(key => isNaN(Number(key))) filters out the numeric values.
  • map(key => States[key as keyof typeof States]) maps the keys to their corresponding enum values.
Get All Enum Values in TypeScript

Check out: Avoid Duplicate Enum Values in TypeScript

Using a Utility Function in TypeScript

For better reusability and readability, you can create a utility function to get all enum values. This is particularly useful if you need to retrieve enum values in multiple places in your code.

enum States {
    California,
    Texas,
    Florida,
    NewYork,
}

function getEnumValues<T extends object>(enumObj: T): string[] {
    return Object.keys(enumObj)
        .filter(key => isNaN(Number(key))) 
        .map(key => enumObj[key as keyof T] as unknown as string); 
}

const stateValues = getEnumValues(States);

console.log(stateValues); // Output: [ 'California', 'Texas', 'Florida', 'NewYork' ]

This utility function, getEnumValues, can be used with any enum, making your code more modular and maintainable.

Using a Utility Function in TypeScript

Check out: Difference Between Undefined and Null In TypeScript

Handling String Enums in TypeScript

If you are working with string enums, the approach is slightly different but follows the same basic principles. Here’s an example:

enum Cities {
    LosAngeles = "Los Angeles",
    Houston = "Houston",
    Miami = "Miami",
    NewYorkCity = "New York City",
}

const cityValues = Object.keys(Cities)
    .map(key => Cities[key as keyof typeof Cities]);

console.log(cityValues); // Output: [ 'Los Angeles', 'Houston', 'Miami', 'New York City' ]

In this case, you don’t need to filter out numeric keys because string enums only have string values.

Handling String Enums in TypeScript

Check out: Use TypeScript Enums with Functions

Iterating Over Enum Values in TypeScript

Sometimes, you might need to iterate over enum values to perform certain actions. Here’s how you can do it:

enum Departments {
    Sales,
    Marketing,
    Engineering,
    HR,
}

Object.values(Departments)
    .filter(value => typeof value === 'string')
    .forEach(department => {
        console.log(department);
    });

// Output:
// Sales
// Marketing
// Engineering
// HR

This code snippet iterates over the enum values and logs each department to the console.

Iterating Over Enum Values in TypeScript

Real-World Example: Populating a Dropdown

Let’s consider a real-world example where you need to populate a dropdown list with enum values. This is a common use case in forms where users need to select from a predefined list of options.

enum JobTitles {
    SoftwareEngineer,
    ProductManager,
    Designer,
    DataScientist,
}

function createDropdownOptions(enumObj: any) {
    return Object.keys(enumObj)
        .filter(key => isNaN(Number(key)))
        .map(key => `<option value="${key}">${enumObj[key]}</option>`)
        .join('');
}

const dropdownHTML = createDropdownOptions(JobTitles);
document.getElementById('job-titles-dropdown').innerHTML = dropdownHTML;

In this example, the createDropdownOptions function generates HTML <option> elements for each enum value and populates a dropdown list.

Conclusion

Enums are a powerful feature in TypeScript that can help you manage a set of related values more effectively. Retrieving all values of an enum is a common requirement, and as we’ve seen, it can be achieved easily using Object.keys() and Object.values().

Whether you are populating a dropdown, validating input, or simply logging values, these methods provide a flexible and efficient way to work with enums.

By understanding and utilizing these techniques, you can make your TypeScript code more robust, readable, and maintainable.

You may like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.