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.
Complete Code
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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.