How to Convert a String to Enum in TypeScript

To convert a string to an enum in TypeScript, you can use the “enum’s string values”.

Here’s a step-by-step guide to help you achieve this:

Step 1: Define the Enum

enum MyEnum {
  ValueA = "VALUE_A",
  ValueB = "VALUE_B",
  ValueC = "VALUE_C",
}

Step 2: Create a function to convert the string to the Enum type

function stringToEnum(value: string): MyEnum | null {
  if (Object.values(MyEnum).indexOf(value) >= 0) {
    return value as MyEnum;
  }
  return null;
}

Step 3: Use the function to convert a string to the Enum

const stringValue: string = "VALUE_A";
const enumValue: MyEnum | null = stringToEnum(stringValue);

if (enumValue !== null) {
  console.log("Converted string to Enum:", enumValue);
} else {
  console.log("Invalid string value");
}

In this code, Object.values(MyEnum).includes(value) checks if the given value exists in the Enum’s values. If it does, the function returns the value as the Enum type. If not, it returns null.

Example

enum MyEnum {
  ValueA = "VALUE_A",
  ValueB = "VALUE_B",
  ValueC = "VALUE_C",
}

function stringToEnum(value: string): MyEnum | null {
  if (Object.values(MyEnum).includes(value)) {
    return value as MyEnum;
  }
  return null;
}

let stringValue: string = "VALUE_A";
const enumValue: MyEnum | null = stringToEnum(stringValue);

if (enumValue !== null) {
  console.log("Converted string to Enum:", enumValue);
} else {
  console.log("Invalid string value");
}

That’s it.

Leave a Comment