How to Convert String to Enum in Typescript?

Recently, while working with Typescript enums, I got a requirement to convert string to enum. In this Typescript tutorial, I will explain different methods to convert string to enum in Typescript.

Converting a string to an enum in TypeScript can be achieved by accessing the enum using the string as a key after ensuring it matches an enum member. For a case-insensitive conversion, you can compare lowercased keys of the enum against the lowercased string. If the string is valid, the corresponding enum value is returned; otherwise, an error is thrown to handle invalid strings.

Understanding Enums in TypeScript

Before diving into string-to-enum conversion, let’s first understand what enums are in TypeScript. An enum is a special “type” that allows you to define a set of named constants. These constants can be either numeric or string-based.

Here’s a simple numeric enum:

enum Direction {
  Up = 1,
  Down,
  Left,
  Right
}

And here’s a string enum:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}

TypeScript will auto-increment the following values in the numeric enum if you don’t explicitly assign one. So Down would be 2, Left would be 3, and so on. For the string enum, each member must be initialized with a string value.

Convert String to Enum in Typescript

Now, let us check how to convert a string to an enum using different methods.

Using the Enum Index Signature

TypeScript enums have an index signature that allows you to access their values by a numeric index or string value. Here’s an example using the Direction string enum:

const value = "UP";
const enumValue = Direction[value as keyof typeof Direction];

In this example, we’re using the keyof typeof operator to ensure that the string we’re trying to convert is actually a key of the Direction enum.

Using a Conversion Function

Another approach is to write a function that validates and converts a string to an enum value. Here’s an example:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}
function toEnumValue(enumObj: any, str: string): any {
  if (str in enumObj) {
    return enumObj[str];
  } else {
    throw new Error(`Invalid value for enum: ${str}`);
  }
}

const direction = toEnumValue(Direction, "UP");

This function checks if the string is a key in the given enum and returns the corresponding enum value if it is. Otherwise, it throws an error.

Using a Generic Function

To make the conversion function safer and reusable, you can use generics:

function toEnumValue<T>(enumObj: T, str: string): T[keyof T] {
  if (str in enumObj) {
    return enumObj[str as keyof T];
  } else {
    throw new Error(`Invalid value for enum: ${str}`);
  }
}

const direction = toEnumValue(Direction, "UP");

This function is now strongly typed and will return the correct enum type.

Handling Case Sensitivity

Enums are case-sensitive, which can sometimes lead to issues if the case of the input string doesn’t match the case of the enum keys. To handle this, you can modify your conversion function to be case-insensitive:

function toEnumValue<T>(enumObj: T, str: string): T[keyof T] {
  const enumKey = Object.keys(enumObj).find(key => key.toLowerCase() === str.toLowerCase());
  if (enumKey) {
    return enumObj[enumKey as keyof T];
  } else {
    throw new Error(`Invalid value for enum: ${str}`);
  }
}

const direction = toEnumValue(Direction, "up"); // This will now work even with "up" in lowercase.

Using a Switch Statement

If you prefer not to use a dynamic approach, you can explicitly map strings to enum values using a switch statement:

enum Direction {
  Up = "UP",
  Down = "DOWN",
  Left = "LEFT",
  Right = "RIGHT"
}
function stringToEnum(str: string): Direction | undefined {
  switch (str) {
    case "UP":
      return Direction.Up;
    case "DOWN":
      return Direction.Down;
    case "LEFT":
      return Direction.Left;
    case "RIGHT":
      return Direction.Right;
    default:
      return undefined; // or throw an error if you prefer
  }
}

const direction = stringToEnum("UP");

This method is more verbose but useful if you want complete control over the conversion process and perhaps handle some strings differently.

Conclusion

In this Typescript tutorial, I have explained various methods of how to convert Strings to enums in Typescript.

You may also like:

>