Convert String to Enum in TypeScript [4 Methods]

Recently, I was working on a TypeScript development project where we wanted to convert a string to an enum. This is a common requirement for TypeScript developers. In this tutorial, I will explain various methods for converting strings to enums in TypeScript with real examples.

What are TypeScript Enums?

Before diving into the conversion methods, let’s understand what enums are in TypeScript:

enum Direction {
  North = "NORTH",
  South = "SOUTH",
  East = "EAST",
  West = "WEST"
}

Enums in TypeScript can be string-based or numeric-based, providing a way to define a set of named constants. They make your code more readable and help catch errors at compile time.

Convert String to Enum in TypeScript

Now, let me show you four different methods to convert string to enum in TypeScript.

Method 1: Using Type Assertion

The simplest method to convert a string to an enum in TypeScript is through type assertion. Here is the complete example.

enum Color {
  Red = "RED",
  Green = "GREEN",
  Blue = "BLUE"
}

// Converting a string to enum
const colorString = "RED";
const colorEnum = colorString as Color;
console.log(colorEnum);

This method works well for simple conversions but doesn’t provide any validation. If the string doesn’t match any enum value, TypeScript won’t catch this error at compile time.

You can see the exact output in the screenshot below:

typescript string to enum

Check out How to Iterate Over Enums in TypeScript?

Method 2: Using Enum Index Access

Now, let me show you another method to convert a string to enum in TypeScript.

This method is a more type-safe approach, and it involves using the enum itself as an object. Here is the complete code.

enum Season {
  Spring = "SPRING",
  Summer = "SUMMER",
  Fall = "FALL",
  Winter = "WINTER"
}

function stringToEnum(value: string): Season | undefined {
  return (Object.values(Season) as Array<Season>).includes(value as Season)
    ? value as Season
    : undefined;
}

const mySeason = stringToEnum("SUMMER"); // Returns Season.Summer
const invalidSeason = stringToEnum("NOT_A_SEASON"); // Returns undefined
console.log(mySeason);
console.log(invalidSeason);

This method provides validation and returns undefined if the string doesn’t match any enum value.

This time, I executed the TypeScript code using an online TypeScript editor, and you can see the exact output in the screenshot below:

typescript convert string to enum

Check out TypeScript String to Number Conversion

Method 3: Using keyof typeof for Reverse Mapping

TypeScript enums create reverse mappings that can be leveraged for conversions:

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

function convertStringToEnum<T>(
  enumObject: T,
  value: string
): T[keyof T] | undefined {
  const enumValues = Object.values(enumObject) as string[];
  const index = enumValues.indexOf(value);
  return index !== -1 ? Object.values(enumObject)[index] as T[keyof T] : undefined;
}

const role = convertStringToEnum(UserRole, "EDITOR"); // Returns UserRole.Editor
console.log(role);

This approach is type-safe and flexible, working with any enum type.

I executed the above TypeScript code, and you can see the exact output in the screenshot below:

typescript cast string to enum

Read Get Distinct Values from an Array in TypeScript

Method 4: Using Object.keys for Validation

When dealing with string enums, we can use Object.keys to validate strings before conversion:

enum PaymentMethod {
  CreditCard = "CREDIT_CARD",
  DebitCard = "DEBIT_CARD",
  PayPal = "PAYPAL",
  Venmo = "VENMO"
}

function isValidEnumValue<T>(enumObject: T, value: string): boolean {
  return Object.values(enumObject).includes(value);
}

function safeStringToEnum<T>(enumObject: T, value: string): T[keyof T] | null {
  if (isValidEnumValue(enumObject, value)) {
    return value as unknown as T[keyof T];
  }
  return null;
}

const method = safeStringToEnum(PaymentMethod, "PAYPAL"); // Returns PaymentMethod.PayPal
console.log(method);

This method provides explicit validation and returns null for invalid values, making error handling clearer.

Here is the exact output in the screenshot below:

convert string to enum typescript

Check out Set Default Values in TypeScript Interfaces

Real-World Example: Processing API Responses

Let’s look at a practical example where we fetch user data from an API and convert string values to enums:

enum UserStatus {
  Active = "ACTIVE",
  Inactive = "INACTIVE",
  Suspended = "SUSPENDED",
  Pending = "PENDING"
}

interface ApiResponse {
  id: number;
  name: string;
  status: string;
}

async function fetchUser(userId: number): Promise<{
  id: number;
  name: string;
  status: UserStatus | null;
}> {
  // Simulated API call
  const response: ApiResponse = await fetch(`/api/users/${userId}`)
    .then(res => res.json());

  return {
    id: response.id,
    name: response.name,
    status: safeStringToEnum(UserStatus, response.status)
  };
}

Check out How to Check if a String is Empty in TypeScript?

Handling Numeric Enums

While string enums are common, numeric enums require a different approach:

enum DaysOfWeek {
  Sunday = 0,
  Monday = 1,
  Tuesday = 2,
  Wednesday = 3,
  Thursday = 4,
  Friday = 5,
  Saturday = 6
}

function stringToNumericEnum(value: string): DaysOfWeek | undefined {
  const enumKey = Object.keys(DaysOfWeek).find(
    key => key.toLowerCase() === value.toLowerCase()
  );

  return enumKey ? DaysOfWeek[enumKey as keyof typeof DaysOfWeek] : undefined;
}

const day = stringToNumericEnum("monday"); // Returns DaysOfWeek.Monday (1)

Best Practices for Enum Conversion

Based on my experience, here are some best practices to follow:

  1. Always validate input strings before conversion to avoid runtime errors
  2. Use type-safe conversion methods that leverage TypeScript’s type system
  3. Handle invalid values gracefully by returning undefined or null
  4. Consider case sensitivity in your conversion logic
  5. Document your conversion functions for team understanding

Read How to Check if a String Contains a Substring in TypeScript?

Compare Different Approaches

Here’s a comparison of the methods we’ve covered:

MethodType SafetyValidationFlexibilityUse Case
Type AssertionLowNoneHighQuick conversions in trusted code
Enum Index AccessMediumBasicMediumGeneral purpose conversion
keyof typeofHighBuilt-inHighComplex type relationships
Object.keysHighExplicitHighWhen validation is critical

Common Issues to Avoid While Converting

When converting strings to enums, watch out for these common issues:

  • Case sensitivity: Enum values are often uppercase, but input strings might not be
  • Undefined behavior: Not handling invalid inputs can lead to runtime errors
  • Type erasure: TypeScript enums exist only at compile time, not runtime

Conclusion

In this tutorial, I explained how to convert strings to enums in TypeScript using different methods:

  • Using Type Assertion
  • Using Enum Index Access
  • Using keyof typeof for Reverse Mapping
  • Using Object.keys for Validation

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.

Live Webinar

Quiz App Using SharePoint Framework (SPFx)

Learn to built a complete Quiz Management solution that enables admins to create and manage quizzes, categories, questions, and settings with an easy automated setup process in SharePoint. It also includes an interactive quiz experience for users and a powerful dashboard to track participation, analyze results, and view detailed performance reports with charts and answer insights.

📅 2nd June 2026 – 10:00 AM EST | 7:30 PM IST

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