How to Get Enum by Name in TypeScript – 5 Easy Methods

In TypeScript, enums provide a powerful way to define named constants, but sometimes you need to access an enum value using its name as a string.

Over my years of TypeScript development, I’ve learned several reliable methods to get enum values by their name. In this article, I’ll walk through 5 practical approaches to get an enum by name in TypeScript.

What Are TypeScript Enums?

Before diving into the solutions, let me explain what enums are in TypeScript.

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

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

Enums provide a way to define a set of named constants. They make your code more readable and help catch errors at compile time.

Now, let’s look at different ways to get an enum value by its name in TypeScript.

Method 1: Using Square Bracket Notation

The simplest way to get an enum value by its name is using square bracket notation. Here is a TypeScript example.

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

// Get enum value by name
const stateName = "California";
const stateCode = USState[stateName]; // "CA"

console.log(stateCode); // Outputs: "CA"

However, there’s a catch with string enums. Direct indexing works differently for string enums versus numeric enums.

For numeric enums, TypeScript creates a reverse mapping that allows you to look up the name by value and vice versa. For string enums, only name-to-value mapping is created automatically.

Here is the exact output in the screenshot below:

Get Enum by Name in TypeScript

Check out Convert Enums to Strings in TypeScript

Method 2: Using Type Assertion with keyof typeof

For a more type-safe approach, you can use keyof typeof with type assertions. Here is the complete example and the TypeScript code.

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

function getEnumValueByName<T extends object>(enumObject: T, keyName: string): T[keyof T] | undefined {
  const key = keyName as keyof typeof enumObject;
  return key in enumObject ? enumObject[key] : undefined;
}

// Usage
const stateCode = getEnumValueByName(USState, "California");
console.log(stateCode); // Outputs: "CA"

This method provides better type safety and works with both string and numeric enums.

You can see the exact output in the screenshot below:

typescript get enum by name

Check out TypeScript Switch with Enums

Method 3: Using Object Indexing with Type Guards

A more robust approach is to use type guards to ensure the key exists in TypeScript.

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

function getEnumValue<T>(enumObj: T, enumKey: string): T[keyof T] | undefined {
  if (Object.keys(enumObj).includes(enumKey)) {
    return enumObj[enumKey as keyof T];
  }
  return undefined;
}

// Usage
const result = getEnumValue(USState, "California");
console.log(result); // Outputs: "CA"

This method is safer because it checks if the key exists before attempting to access it.

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

Method 4: Using a Generic Utility Function

Here’s a more generic utility function that works with any enum type. Here is the generic utility function to get an enum by name in TypeScript.

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

function getEnumByName<T extends Record<string, string | number>>(
  enumObject: T,
  enumName: string
): T[keyof T] | undefined {
  // Check if the name exists in the enum
  if (enumName in enumObject) {
    return enumObject[enumName as keyof T];
  }
  return undefined;
}

// Usage with our USState enum
const texasCode = getEnumByName(USState, "Texas");
console.log(texasCode); // Outputs: "TX"

// Using with numeric enum
enum UserRole {
  Admin = 0,
  Editor = 1,
  Viewer = 2
}

const adminRole = getEnumByName(UserRole, "Admin");
console.log(adminRole); // Outputs: 0

This utility function provides type safety and works consistently across different enum types.

You can see the exact output in the screenshot below:

How to Get Enum by Name in TypeScript

Check out How to Use TypeScript Enum Reverse Mapping

Method 5: Using Reflection with Object.entries()

For more complex scenarios, you might want to use Object.entries() to dynamically find the enum value:

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

function findEnumValueByName<T extends object>(enumObject: T, name: string): T[keyof T] | undefined {
  const entries = Object.entries(enumObject);
  for (const [key, value] of entries) {
    if (key === name) {
      return value as T[keyof T];
    }
  }
  return undefined;
}

// Usage
const floridaCode = findEnumValueByName(USState, "Florida");
console.log(floridaCode); // Outputs: "FL"

This approach is more flexible and can be extended to handle case-insensitive lookups or partial matches.

Handle Non-Existent Enum Names

It’s important to handle cases where the provided enum name doesn’t exist. Here’s a robust implementation that includes error handling:

function getEnumValueSafely<T extends object>(
  enumObj: T,
  enumName: string,
  defaultValue?: T[keyof T]
): T[keyof T] | undefined {
  if (enumName in enumObj) {
    return enumObj[enumName as keyof T];
  }

  console.warn(`Enum name '${enumName}' does not exist in the provided enum.`);
  return defaultValue;
}

// Usage with default value
const result = getEnumValueSafely(USState, "Montana", USState.California);
console.log(result); // Outputs: "CA" (default value)

This function provides a default value if the enum name doesn’t exist, making your code more robust.

Check out Convert TypeScript Enums to Arrays

Real-World Example: User Permission System

Let’s see how this might be used in a real-world scenario like a user permission system for a U.S.-based SaaS application:

enum UserPermission {
  ViewReports = "view_reports",
  EditProfiles = "edit_profiles",
  ManageUsers = "manage_users",
  AccessBilling = "access_billing"
}

// User configuration from database or JSON
const userConfig = {
  name: "Jane Smith",
  email: "jane@example.com",
  permissions: ["ViewReports", "AccessBilling"]
};

// Convert permission names to actual permission values
const userPermissions = userConfig.permissions.map(permName => 
  getEnumByName(UserPermission, permName)
).filter(Boolean);

console.log(userPermissions); 
// Outputs: ["view_reports", "access_billing"]

// Check if user has specific permission
function hasPermission(permissionName: string): boolean {
  const permValue = getEnumByName(UserPermission, permissionName);
  return userPermissions.includes(permValue);
}

console.log(hasPermission("ViewReports")); // true
console.log(hasPermission("ManageUsers")); // false

This example shows how you might use enum name lookups in a permission system where permission names are stored as strings but need to be converted to enum values for use in your application.

Read Check If a String Is in an Enum in TypeScript

Performance Considerations in TypeScript

When working with large enums or in performance-critical code, it’s worth noting that methods using Object.keys(), Object.entries(), or similar functions may have slightly higher overhead.

For the best performance in critical sections, consider using direct indexing (Method 1) if you can guarantee the enum name exists, or pre-compute a lookup map if you need to do many lookups.

I hope you learn how to get an enum by name in TypeScript. Whether you’re building enterprise applications or small projects, these techniques will help you work more effectively with TypeScript enums.

If you have any questions or suggestions, please feel free to leave them in the comments below.

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