How to Get Enum Key by Value in TypeScript

While building an e-commerce admin dashboard in TypeScript, you define an enum called ProductCategory to manage all category types consistently across your app.

This enum helps when filtering, tagging, or assigning categories to products during development. However, fetching product data from an external API returns only the category value (not the enum key).

So, in this tutorial, I will explain how to get the Enum key by value in TypeScript.

Enums are a powerful TypeScript feature that allows developers to define a set of named constants. However, there may be situations where you need to find the enum key based on a given value. We’ll explore different techniques to accomplish this task effectively.

Understand Enums in TypeScript

Before diving into the solution, let’s briefly understand what enums are in TypeScript. Enums provide a way to define a collection of related constants with meaningful names. They can be used to create a set of distinct cases or to document intent more clearly.

Here’s an example of an enum representing different states in the United States:

enum USState {
  CALIFORNIA = "CA",
  TEXAS = "TX",
  NEW_YORK = "NY",
  FLORIDA = "FL"
}

In this enum, each key represents a state, and the corresponding value is the two-letter abbreviation of that state.

Check out: Convert TypeScript Enums to Arrays

Get Enum Key by Value in TypeScript

Now, let’s address the main problem: how to get the enum key by its value in TypeScript. There are a couple of approaches we can use to achieve this.

Approach 1: Using Object.keys() and Object.values() Methods in TypeScript

One way to retrieve the enum key by value is by utilizing the Object.keys() and Object.values() methods in JavaScript. Here’s how you can do it:

enum USState {
  CALIFORNIA = "CA",
  TEXAS = "TX",
  NEW_YORK = "NY",
  FLORIDA = "FL"
}

function getEnumKeyByValue(enumObj: any, enumValue: string): string | undefined {
  const enumKey = Object.keys(enumObj)[Object.values(enumObj).indexOf(enumValue)];
  return enumKey;
}

const stateValue = "NY";
const stateKey = getEnumKeyByValue(USState, stateValue);
console.log(stateKey); // Output: "NEW_YORK"

In this example, we define a function called getEnumKeyByValue that takes an enum object and an enum value as parameters.

Inside the function, we use Object.keys() to get an array of the enum keys and Object.values() to get an array of the enum values. Then, we find the index of the specified enum value using indexOf() and use that index to retrieve the corresponding enum key from the keys array.

Get Enum Key by Value in TypeScript

Check out: TypeScript Enums vs String Literal Unions

Approach 2: Using a Reverse Mapping Object in TypeScript

Another approach is to create a reverse mapping object that maps the enum values back to their respective keys. Here’s an example:

enum USState {
  CALIFORNIA = "CA",
  TEXAS = "TX",
  NEW_YORK = "NY",
  FLORIDA = "FL"
}

const reverseUSState: { [key: string]: string } = {};

for (const key in USState) {
  if (Object.prototype.hasOwnProperty.call(USState, key)) {
    const enumKey = key as keyof typeof USState;
    reverseUSState[USState[enumKey]] = enumKey;
  }
}

// Usage
const stateValue = "FL";
const stateKey = reverseUSState[stateValue];
console.log(stateKey); // Output: "FLORIDA"

In this approach, we create an object called reverseUSState that will store the reverse mapping of enum values to keys. We iterate over the enum keys using a for…in loop and check if the enum has the current key using hasOwnProperty().

If it does, we assign the enum value as the key and the enum key as the value in the reverseUSState object.

To retrieve the enum key by value, we simply access the reverseUSState object using the enum value as the key.

Get Enum Key by Using a Reverse Mapping Object in TypeScript

Check out: Convert TypeScript Enum to String

Real-World Example

Let’s consider a real-world scenario where retrieving the enum key by value can be useful. Suppose you have an e-commerce website that sells products across different states in the USA. Each state has its own tax rate, represented by an enum:

enum USTaxRate {
  CALIFORNIA = 0.0825,
  TEXAS = 0.0625,
  NEW_YORK = 0.04,
  FLORIDA = 0.06
}

Now, imagine you have a function that calculates the total price of a product based on its base price and the state’s tax rate. You receive the state information as a string value (e.g., “CA” for California). To determine the tax rate, you need to find the corresponding enum key for that state value.

function calculateTotalPrice(basePrice: number, stateValue: string): number {
  const stateKey = Object.keys(USTaxRate)[Object.values(USTaxRate).indexOf(stateValue)];
  const taxRate = USTaxRate[stateKey];
  const totalPrice = basePrice * (1 + taxRate);
  return totalPrice;
}

const productPrice = 100;
const stateValue = "TX";
const totalPrice = calculateTotalPrice(productPrice, stateValue);
console.log(totalPrice); // Output: 106.25

In this example, we use the getEnumKeyByValue function from Approach 1 to find the enum key based on the state value. Once we have the enum key, we can access the corresponding tax rate from the USTaxRate enum. Finally, we calculate the total price by multiplying the base price by (1 + taxRate).

Get Enum Key from Value in TypeScript

Conclusion

In this tutorial, we explored how to retrieve the enum key by value in TypeScript. We discussed two approaches: using Object.keys() and Object.values(), and creating a reverse mapping object. Both methods allow you to find the enum key based on a given value efficiently.

Understanding how to work with enums and retrieve keys by values can be valuable in various scenarios, such as mapping values to meaningful names, handling user input, or performing lookups based on specific values.

Remember to choose the approach that best fits your specific use case and coding style. With the techniques explained in this tutorial, you can confidently retrieve enum keys by values in your TypeScript projects.

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.