How to Convert Enums to Strings in TypeScript?

When working with TypeScript, I often need to convert enum values to their string representations. This is especially common for TypeScript developers when displaying enum values in a user interface or serializing data for API calls.

In this tutorial, I will explain several reliable methods to convert enums to strings in TypeScript with examples.

Let’s dive into the different techniques!

What Are Enums in TypeScript?

Let’s quickly understand what enums are in TypeScript.

Enums allow us to define a set of named constants. They make our code more readable and help us work with a fixed set of values.

Here’s a basic example of a numeric enum:

enum Direction {
  North = 0,
  East = 1,
  South = 2,
  West = 3
}

And here’s a string enum:

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

Now let’s look at how to convert these enum values to strings in TypeScript with examples.

Method 1: Using Object Indexing for Numeric Enums

One of the interesting features of TypeScript is that numeric enums create a reverse mapping automatically. This means we can access the enum name by its value:

enum Direction {
  North = 0,
  East = 1,
  South = 2,
  West = 3
}

// Convert enum value to string
const directionName: string = Direction[Direction.East]; // "East"
console.log(directionName); // Output: East

This approach is simple and works well for numeric enums. However, it doesn’t work for string enums out of the box.

You can see the exact output in the screenshot below:

convert enum to string typescript

Check out TypeScript Switch with Enums

Method 2: Using Object.keys() with TypeScript’s keyof and typeof

For a more generic approach that works with both numeric and string enums, we can use Object.keys(). Here is the complete TypeScript code.

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

function getEnumKeyByValue<T extends {[index: string]: string}>(myEnum: T, enumValue: string): keyof T | null {
  const keys = Object.keys(myEnum).filter(x => myEnum[x] === enumValue);
  return keys.length > 0 ? keys[0] : null;
}

const stateName = getEnumKeyByValue(USState, "NY");
console.log(stateName); // Output: NewYork

This method works for string enums, but it requires a bit more code.

Here is the exact output in the screenshot below:

convert enum to string in typescript

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

Method 3: Creating a Utility Function for Numeric Enums

Let’s create a more robust utility function for converting numeric enum values to strings:

function enumToString<T extends object>(enumObj: T, value: number): string | undefined {
  return Object.entries(enumObj)
    .find(([key, val]) => val === value)?.[0];
}

enum Direction {
  North = 0,
  East = 1,
  South = 2,
  West = 3
}

const direction = Direction.South;
const directionName = enumToString(Direction, direction);
console.log(directionName); // Output: South

This function is more flexible and handles cases where the enum value might not exist.

Now, you can see the exact output in the screenshot below after I executed the above TypeScript code using VS Code.

typescript convert enum to string

Read Convert TypeScript Enums to Arrays

Method 4: Using Enum Reverse Mapping with TypeScript

For numeric enums, TypeScript generates reverse mappings automatically. We can use this feature directly:

enum UserRole {
  Admin = 0,
  Editor = 1,
  Viewer = 2
}

function getEnumNameByValue(enumType: any, value: number): string | undefined {
  return enumType[value];
}

const roleName = getEnumNameByValue(UserRole, 1);
console.log(roleName); // Output: Editor

This approach is clean and straightforward for numeric enums.

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

Method 5: Create Bidirectional Maps for String Enums

String enums don’t have reverse mappings like numeric enums do. We can create a bidirectional map to solve this:

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

const stateNameByCode = new Map<string, string>();

// Initialize the map
Object.entries(USState).forEach(([key, value]) => {
  if (typeof value === 'string') {
    stateNameByCode.set(value, key);
  }
});

// Get state name from code
const stateName = stateNameByCode.get("TX");
console.log(stateName); // Output: Texas

This approach is more explicit and works well for string enums.

Check out TypeScript Enum Naming Conventions

Method 6: Using TypeScript’s Built-in Features for Type Safety

We can leverage TypeScript’s type system to ensure type safety when converting enums to strings:

enum PaymentMethod {
  CreditCard = "credit_card",
  BankTransfer = "bank_transfer",
  PayPal = "paypal"
}

type PaymentMethodKeys = keyof typeof PaymentMethod;

function getEnumKeyByEnumValue(enumValue: PaymentMethod): PaymentMethodKeys | undefined {
  const keys = Object.keys(PaymentMethod) as PaymentMethodKeys[];
  return keys.find(key => PaymentMethod[key] === enumValue);
}

const methodName = getEnumKeyByEnumValue(PaymentMethod.PayPal);
console.log(methodName); // Output: PayPal

This approach gives us the best of both worlds: type safety and reliable enum-to-string conversion.

Check out Convert String to Enum in TypeScript

Real-World Example: E-commerce Order Status

Let’s use a practical example from an e-commerce application, where I have converted enums to a string.

enum OrderStatus {
  Pending = 0,
  Processing = 1,
  Shipped = 2,
  Delivered = 3,
  Canceled = 4
}

// Function to get user-friendly status text
function getOrderStatusText(status: OrderStatus): string {
  return OrderStatus[status] || "Unknown Status";
}

// Usage in a component
function OrderDetails() {
  const orderStatus = OrderStatus.Shipped;
  const statusText = getOrderStatusText(orderStatus);

  return `
    <div class="order-status">
      Status: <span class="status-${orderStatus}">${statusText}</span>
    </div>
  `;
}

console.log(OrderDetails());
// Output: <div class="order-status">Status: <span class="status-2">Shipped</span></div>

This example shows how you might use enum-to-string conversion in a real application to display user-friendly status messages.

Method 3 (utility function) or Method 6 (type-safe approach) will provide the best balance of flexibility and reliability for most applications.

I’ve used these methods in numerous production applications, from financial dashboards to healthcare systems.

Next time you need to convert an enum to a string in your TypeScript project, I hope one of these methods will help you solve the problem efficiently.

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