Recently, I was working on a TypeScript project where I needed to convert numeric values back to their corresponding enum names. This is when I researched and found out enum reverse mapping feature.
While most developers know how to get enum values from keys, going the other way around isn’t as widely understood.
In this article, I’ll share everything I’ve learned about TypeScript enum reverse mapping after using it in numerous production applications. I’ll cover what it is, how it works, and provide practical examples that you can start using right away.
Let’s dive in!
What is TypeScript Enum Reverse Mapping?
Enum reverse mapping allows you to look up an enum’s key name by using its value. This is particularly useful when you’re receiving numeric values from an API or database and need to convert them back to their human-readable string representation.
TypeScript automatically generates this reverse mapping for numeric enums, but not for string enums (an important distinction we’ll explore later).
How Numeric Enum Reverse Mapping Works in TypeScript
When you define a numeric enum in TypeScript, the compiler actually generates code that creates a bidirectional mapping.
Let me show you a basic example:
enum HttpStatus {
OK = 200,
NotFound = 404,
InternalServerError = 500
}
// Regular mapping (key → value)
console.log(HttpStatus.OK); // Outputs: 200
// Reverse mapping (value → key)
console.log(HttpStatus[200]); // Outputs: "OK"
This reverse mapping works because TypeScript generates JavaScript code that creates both a forward and reverse lookup object.
The compiled JavaScript looks something like this:
var HttpStatus;
(function (HttpStatus) {
HttpStatus[HttpStatus["OK"] = 200] = "OK";
HttpStatus[HttpStatus["NotFound"] = 404] = "NotFound";
HttpStatus[HttpStatus["InternalServerError"] = 500] = "InternalServerError";
})(HttpStatus || (HttpStatus = {}));
Notice how for each enum member, TypeScript creates both HttpStatus["OK"] = 200 and HttpStatus[200] = "OK".
Practical Example: User Roles Management
Let’s look at a real-world example. Imagine you’re building a user management system for a SaaS application and storing user roles as numbers in your database:
enum UserRole {
Admin = 1,
Manager = 2,
Editor = 3,
Viewer = 4
}
// When retrieving a user from the database
const userRoleFromDatabase = 2;
// Convert numeric role to string representation
const roleString = UserRole[userRoleFromDatabase]; // "Manager"
console.log(`Current user has ${roleString} privileges`);
This is much more readable than displaying raw numeric values to users!
Here is the exact output in the screenshot below:

Check out How to Iterate Over Enums in TypeScript?
String Enums Don’t Have Reverse Mapping in TypeScript
It’s important to note that string enums do not have automatic reverse mapping. If you try to use reverse mapping with string enums, it won’t work:
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT"
}
console.log(Direction.Up); // "UP" - works fine
console.log(Direction["UP"]); // undefined - reverse mapping doesn't work!
The reason is that string enums don’t generate the bidirectional lookup code that numeric enums do.
But here are a few methods you can follow reverse mapping for string enums in TypeScript.
Method 1: Create Reverse Mapping for String Enums Manually
If you need reverse mapping for string enums, you can create it manually. Here’s how:
enum ProductCategory {
Electronics = "ELECTRONICS",
Clothing = "CLOTHING",
Books = "BOOKS"
}
// Create a reverse mapping object
const CategoryReverse: Record<string, ProductCategory> = {};
for (const key in ProductCategory) {
const value = ProductCategory[key as keyof typeof ProductCategory];
if (typeof value === 'string') {
CategoryReverse[value] = key as unknown as ProductCategory;
}
}
// Now you can use it for reverse lookup
console.log(CategoryReverse["ELECTRONICS"]); // "Electronics"
You can see the output in the screenshot below:

Check out Convert String to Enum in TypeScript
Method 2: Using Object.entries() for Reverse Lookup
Another approach is to use Object.entries() to create a lookup function:
enum PaymentStatus {
Pending = "PENDING",
Completed = "COMPLETED",
Failed = "FAILED",
Refunded = "REFUNDED"
}
function getKeyByValue(enumObj: any, value: string): string | undefined {
const entries = Object.entries(enumObj).filter(([_, val]) => val === value);
return entries.length > 0 ? entries[0][0] : undefined;
}
const status = "COMPLETED";
console.log(getKeyByValue(PaymentStatus, status)); // "Completed"
This approach is more flexible as it doesn’t require creating a permanent reverse mapping object.
Method 3: Type-Safe Reverse Mapping with TypeScript 4.1+
With TypeScript 4.1 and above, you can use template literal types to create a more type-safe reverse mapping solution:
enum StateCode {
California = "CA",
Texas = "TX",
Florida = "FL",
NewYork = "NY"
}
type ValueOf<T> = T[keyof T];
type KeysMatching<T, V> = { [K in keyof T]-?: T[K] extends V ? K : never }[keyof T];
function getEnumKeyByValue<T, V extends ValueOf<T>>(
enumObj: T,
value: V
): KeysMatching<T, V> {
return Object.keys(enumObj).find(
k => enumObj[k as keyof T] === value
) as KeysMatching<T, V>;
}
// Usage
const state = "CA";
const stateName = getEnumKeyByValue(StateCode, state); // "California"
console.log(`User is from ${stateName}`);
This approach provides better type checking and autocompletion.
Check out TypeScript Enum Naming Conventions
Performance Considerations
When working with large enums, reverse mapping can have performance implications:
- For numeric enums, the reverse mapping is built-in, so lookup is constant time – O(1).
- For custom string enum reverse mappings, the lookup is also O(1) if you pre-build the mapping.
- For methods that search through the enum values (like
getKeyByValue), the complexity is O(n), where n is the number of enum members.
If you’re working with very large enums (hundreds of values) and need frequent reverse lookups, consider pre-computing a reverse mapping object.
Debugging Enum Reverse Mapping
If you’re having issues with enum reverse mapping, here are some common problems and solutions:
Problem 1: Undefined Values
If you’re getting undefined when using reverse mapping:
enum TestEnum {
A = 1,
B = 2
}
console.log(TestEnum[3]); // undefined
The value 3 doesn’t exist in the enum, so it returns undefined. Always check if the value exists in your enum.
Problem 2: Duplicate Values
Be careful with duplicate values in your enums:
enum DuplicateEnum {
A = 1,
B = 1
}
console.log(DuplicateEnum[1]); // "B"
The reverse mapping will only point to the last defined key with that value.
Check out Check If a String Is in an Enum in TypeScript
Real-World Application: API Response Handling
Here’s a practical example of using enum reverse mapping in TypeScript when handling API responses:
enum ErrorCode {
ValidationFailed = 400,
Unauthorized = 401,
NotFound = 404,
ServerError = 500
}
// Simulating an API response
const apiResponse = {
status: "error",
code: 401,
message: "Please log in to continue"
};
function handleApiError(code: number): string {
const errorType = ErrorCode[code];
switch(errorType) {
case "ValidationFailed":
return "Please check your input and try again";
case "Unauthorized":
return "Please log in to continue";
case "NotFound":
return "The requested resource was not found";
case "ServerError":
return "An unexpected error occurred. Please try again later";
default:
return "Unknown error occurred";
}
}
console.log(handleApiError(apiResponse.code)); // "Please log in to continue"
This makes error handling code much more readable and maintainable.
You can see the output in the screenshot below

Conclusion
TypeScript’s enum reverse mapping is a powerful feature that can make your code more readable and maintainable, especially when dealing with numeric values that need human-readable representations.
Remember that reverse mapping works automatically for numeric enums but requires a custom implementation for string enums. In this tutorial, I explained various methods to implement reverse mapping for enums in TypeScript.
I hope you found this article helpful. If you have any questions or suggestions, feel free to leave them in the comments below!
Other TypeScript articles you may also like:
- Convert TypeScript Enums to Arrays
- TypeScript Enum vs Union Type
- How to Get Key by Value from enum String in Typescript

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.