TypeScript Enum Reverse Mapping

While working on a TypeScript project, I got a requirement to map enum values back to their corresponding names, essentially the reverse of how enums are typically used. With numeric enums, TypeScript handles this automatically. But when it came to string enums, I had to implement a custom solution to make reverse mapping work.

In this blog, I’ll explain how to perform enum reverse mapping in TypeScript, covering both numeric and string enums. We’ll look at how reverse mapping works by default, and how to create it manually for string enums.

What is Enum Reverse Mapping?

Enum reverse mapping in TypeScript allows you to map from an enum value back to its name. This is particularly useful when you need to retrieve the name of an enum member based on its value. Reverse mapping is automatically available for numeric enums but requires a bit more work for string enums.

Why Use Enum Reverse Mapping?

Reverse mapping can simplify your code, making it more readable and maintainable. It is especially useful in scenarios where you need to display user-friendly names or labels based on enum values, such as in UI components or logging mechanisms.

Numeric Enums

Numeric enums are the most straightforward type of enums in TypeScript. When you define a numeric enum, TypeScript automatically creates a reverse mapping for you.

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

// Forward mapping
console.log(States.California); // 1

// Reverse mapping
console.log(States[1]); // "California"

Output:

Reverse Enums in TypeScript

In the example above, the States enum maps state names to numeric values. The reverse mapping allows us to retrieve the state name using the numeric value. This feature is built-in and requires no additional code.

Check out: Check if an Enum Contains a Value in TypeScript

String Enums

String enums, on the other hand, do not automatically support reverse mapping. To achieve reverse mapping with string enums, you need to create a custom solution.

enum Cities {
    NewYork = "NY",
    LosAngeles = "LA",
    Chicago = "CHI",
    Houston = "HOU"
}

// Custom reverse mapping
const reverseCities = Object.entries(Cities).reduce((acc, [key, value]) => {
    acc[value] = key;
    return acc;
}, {} as { [key: string]: string });

// Forward mapping
console.log(Cities.NewYork); // "NY"

// Reverse mapping
console.log(reverseCities["NY"]); // "NewYork"

Output:

Reverse Enum Strings in Typescript

In this example, we create a reverseCities object that maps the string values back to their enum names. This approach ensures you can perform reverse lookups with string enums.

Check out: Get Enum Key by Value in TypeScript

Real-World Example: Handling User Roles

Consider a real-world scenario where you need to manage user roles in a web application. Each user role is represented by an enum, and you need to display user-friendly role names in the UI.

Defining the Enum

First, define the enum for user roles:

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

Creating the Reverse Mapping

Next, create a reverse mapping for the UserRole enum:

const reverseUserRole = Object.entries(UserRole).reduce((acc, [key, value]) => {
    acc[value] = key;
    return acc;
}, {} as { [key: string]: string });

Using the Reverse Mapping

Now, you can use the reverse mapping to display user-friendly role names:

function getUserRoleName(role: UserRole): string {
    return reverseUserRole[role];
}
const userRole = UserRole.Admin;
console.log(getUserRoleName(userRole)); 

Output:

Enums reverse mapping in TypeScript

This approach ensures that your code remains clean and maintainable while also providing a seamless way to display user-friendly role names.

Check out: Use TypeScript Enums in Classes

Best Practices for Enum Reverse Mapping

Use Descriptive Names

When defining enums and their reverse mappings, use descriptive names to make your code more readable. Avoid abbreviations or cryptic names that can confuse other developers.

Keep Enums Simple

Enums should be simple and focused. Avoid adding complex logic or unrelated values to your enums. If an enum becomes too complex, consider breaking it down into smaller, more manageable enums.

Validate Enum Values

When working with reverse mappings, always validate enum values to ensure they are valid. This can prevent runtime errors and improve the robustness of your code.

function isValidUserRole(role: string): boolean {
    return role in reverseUserRole;
}

const userRole = "ADMIN";
if (isValidUserRole(userRole)) {
    console.log(getUserRoleName(userRole as UserRole)); // "Admin"
} else {
    console.log("Invalid user role");
}

Document Your Enums

Documenting your enums and their reverse mappings can help other developers understand their purpose and usage. Use comments and TypeScript’s JSDoc annotations to provide clear explanations.

/**
 * Enum representing user roles in the application.
 */
enum UserRole {
    Admin = "ADMIN",
    Editor = "EDITOR",
    Viewer = "VIEWER"
}

/**
 * Reverse mapping for the UserRole enum.
 */
const reverseUserRole = Object.entries(UserRole).reduce((acc, [key, value]) => {
    acc[value] = key;
    return acc;
}, {} as { [key: string]: string });

Conclusion

In this tutorial, we have learned how to use enum reverse mapping in TypeScript with both numeric and string enums. We also learned how numeric enums support reverse mapping out of the box, and how to manually implement reverse mapping for string enums using a simple utility pattern.

We then discussed a real-world example involving user roles, illustrating how reverse mapping can help display user-friendly names in UI or logs.

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.