Published on

How to Convert a String to Enum in TypeScript

Authors
  • Name
    Ripal & Zalak
    Twitter

How to Convert a String to Enum in TypeScript

TypeScript enums are a powerful way to represent a set of related values, improving code readability and type safety. However, working with enums sometimes requires converting a string into its corresponding enum value. In this guide, we’ll explore various methods to achieve this, with clear examples and explanations.

What Are Enums in TypeScript?

Enums in TypeScript are used to define a set of named constants. They can be either numeric or string-based.

Example of a String Enum:

enum Color {
  Red = 'Red',
  Green = 'Green',
  Blue = 'Blue',
}

Why Convert Strings to Enums?

Converting a string to an enum is useful when working with dynamic inputs, such as API responses or user inputs, ensuring they map to predefined values in your code.


Method 1: Simple String-to-Enum Conversion

If your enum’s keys and string values match, you can use a direct mapping.

enum Color {
  Red = 'Red',
  Green = 'Green',
  Blue = 'Blue',
}

const input = 'Green'
const color: Color | undefined = Color[input as keyof typeof Color]

console.log(color) // Output: Green

Explanation:

  • keyof typeof Color ensures the input string is checked against the enum’s keys.
  • If the input matches, it maps to the enum value.
  • This approach works well with string enums.

Method 2: Using Utility Functions

To handle mismatched or invalid inputs, a utility function can be used to validate the string before conversion.

function stringToEnum<T>(enumObj: T, value: string): T[keyof T] | undefined {
  return (Object.values(enumObj) as string[]).includes(value) ? (value as T[keyof T]) : undefined
}

const input = 'Blue'
const color = stringToEnum(Color, input)

console.log(color) // Output: Blue

Benefits:

  • Ensures type safety.
  • Handles invalid values gracefully by returning undefined if no match is found.

Method 3: Using Reverse Mapping (Numeric Enums)

For numeric enums, TypeScript automatically creates reverse mappings. For example:

enum Status {
  Success = 1,
  Failure = 0,
}

const input = 1
const status: Status = Status[input]

console.log(status) // Output: Success

However, reverse mapping does not work with string enums. Use the keyof typeof approach for such cases.


Method 4: Parsing Enums with Complex Values

When enums have complex values (e.g., strings that do not match keys), you can create a parsing function.

function parseEnum<T>(enumObj: T, value: string): T[keyof T] | undefined {
  const entry = Object.entries(enumObj).find(([, v]) => v === value)
  return entry ? (entry[1] as T[keyof T]) : undefined
}

enum Role {
  Admin = 'Administrator',
  User = 'Regular User',
}

const input = 'Administrator'
const role = parseEnum(Role, input)

console.log(role) // Output: Administrator

Key Points:

  • This method ensures the value matches one of the enum’s assigned values.
  • Useful for enums with non-matching keys and values.

Common Pitfalls to Avoid

  1. Using Unsafe Type Assertions: Avoid directly asserting types without validation.

    const color = 'Yellow' as Color // Unsafe! Will not throw errors for invalid values.
    
  2. Ignoring Invalid Inputs: Always validate strings before mapping them to enums.

  3. Overusing Enums: Consider alternatives like union types (type Color = "Red" | "Green" | "Blue") for simpler use cases.


Conclusion

Converting a string to an enum in TypeScript is straightforward when you use the right approach. Whether you’re dealing with simple string enums or complex mappings, the methods outlined above will help you write type-safe, maintainable code.

By implementing these techniques, you can handle dynamic inputs effectively while ensuring your application’s reliability.