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:

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:

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:

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:

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:
- Always validate input strings before conversion to avoid runtime errors
- Use type-safe conversion methods that leverage TypeScript’s type system
- Handle invalid values gracefully by returning undefined or null
- Consider case sensitivity in your conversion logic
- 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:
| Method | Type Safety | Validation | Flexibility | Use Case |
|---|---|---|---|---|
| Type Assertion | Low | None | High | Quick conversions in trusted code |
| Enum Index Access | Medium | Basic | Medium | General purpose conversion |
| keyof typeof | High | Built-in | High | Complex type relationships |
| Object.keys | High | Explicit | High | When 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:
- How to Capitalize the First Letter in TypeScript?
- Format Date in Typescript
- How to Filter An Array with Multiple Conditions 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.