How can I convert a string to an enum in TypeScript?

How can I convert a string to an enum in TypeScript?

I have defined the following enum in TypeScript:

enum Color { Red, Green } In my function, I receive the color as a string. I tried the following code: var green = “Green”; var color: Color = green; // Error: can’t convert string to enum

How can I properly convert a string value to a Color enum using TypeScript? I’m looking for a solution to convert a typescript string to enum.

Hey Archna.vv,

Using a Custom Mapping Function : If you want more control or need to handle cases where the string might not directly map to an enum value, you can create a custom mapping function.

enum Color { Red, Green }

function stringToEnum(value: string): Color | undefined { switch (value) { case “Red”: return Color.Red; case “Green”: return Color.Green; default: return undefined; // or throw an error if you prefer } }

const colorName = “Green”; const color: Color | undefined = stringToEnum(colorName);

console.log(color); // Output: 1 (Green’s numeric value)

Hey Archana,

Using a Custom Mapping Function : If you want more control or need to handle cases where the string might not directly map to an enum value, you can create a custom mapping function.

enum Color { Red, Green }

function stringToEnum(value: string): Color | undefined { switch (value) { case “Red”: return Color.Red; case “Green”: return Color.Green; default: return undefined; // or throw an error if you prefer } }

const colorName = “Green”; const color: Color | undefined = stringToEnum(colorName);

console.log(color); // Output: 1 (Green’s numeric value)