Explain

How do I convert a string to enum in TypeScript?

To convert a string to an enum in TypeScript, you generally need to have a known mapping between the string and the enum member. You can either:

  1. Use a reverse mapping (if it’s a numeric enum), or
  2. Check if the string is a key of the enum (for string-based enums).

Below are typical approaches.

1. Numeric Enum Reverse Mapping

When you have a numeric enum, TypeScript emits both forward and reverse mappings at runtime, so you can do something like:

enum Color {
  Red = 1,
  Green,
  Blue
}

function stringToColor(str: string): Color | undefined {
  // Attempt to use the reverse mapping
  const color = (Color as any)[str];
  return typeof color === "number" ? color : undefined;
}

// Example usage:
console.log(stringToColor("Green")); // 2
console.log(stringToColor("Purple")); // undefined (not in enum)

Explanation:

  • (Color as any)[str] tries to look up the enum member named str.
  • If that is a number, we interpret it as a valid enum member.

Note: The “reverse mapping” trick only works for numeric enums. If Color is a string enum, the generated code doesn’t produce reverse mappings in the same way.

2. String Enum Lookup

With string enums, you don’t get a reverse mapping automatically. Instead, define a function or a dictionary that checks the string against known enum values:

enum Fruit {
  Apple = "APPLE",
  Banana = "BANANA",
  Cherry = "CHERRY"
}

function stringToFruit(str: string): Fruit | undefined {
  // Check if str is one of the enum’s values
  if (Object.values(Fruit).includes(str as Fruit)) {
    return str as Fruit;
  }
  return undefined;
}

// Usage:
console.log(stringToFruit("BANANA"));  // "BANANA"
console.log(stringToFruit("PINEAPPLE")); // undefined

Or you can define a map from string to enum:

const fruitMap: Record<string, Fruit> = {
  APPLE: Fruit.Apple,
  BANANA: Fruit.Banana,
  CHERRY: Fruit.Cherry
};

function toFruit(str: string): Fruit | undefined {
  return fruitMap[str];
}

// Example:
console.log(toFruit("APPLE")); // "APPLE"

3. Summary

  • Numeric enums let you do (EnumType as any)[stringValue] to leverage the auto-generated reverse mapping— if it’s a valid key, you get the numeric value.
  • String enums don’t produce a reverse mapping, so you either:
    • Check membership using Object.values(...), or
    • Maintain a map/dictionary from strings to enum members.

Bonus: If you want to strengthen your JavaScript foundations (which TypeScript builds upon), consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers essential JS patterns (like prototypes, closures, async/await) that will help you use TypeScript’s advanced features more effectively.

Recommended Courses