To be able to convert a string to an enum, you can use some methods like passing the string to an enum object, using "keyof typeof"
or using type assertion. In this article, our experts will show you how to do it with easy-understanding examples and clear explanations.
Ways to convert a string to enum in TypeScript
To be able to convert a string to an enum in TypeScript, we can either pass the string to be converted directly into square brackets or we can use some method of casting.
Passing the string to the enum
We can directly pass the string into the square brackets of the enum object. Then the string will become an element of the enum.
Example:
enum DaysOfWeek { Mondays = 0, Tuesdays = 1, Wednesdays = 2, Thursdays = 3, Fridays = 4, Saturdays = 5, Sundays = 6, } // Pass string to enum object const sundaysEnum = DaysOfWeek["Sundays"]; console.log(sundaysEnum);
Output:
6
In the above example, we declare an enum as the days of the week. Then we pass the string "Sundays"
as a key into the enum object. If there are Sundays in the enum, we have done the conversion. If not, an error message will be displayed.
Using “keyof typeof”
We can use "keyof typeof"
to get enum’s data type as string.
Example:
enum DaysOfWeek { Mondays = 0, Tuesdays = 1, Wednesdays = 2, Thursdays = 3, Fridays = 4, Saturdays = 5, Sundays = 6, } // Using "keyof typeof" to convert a string to enum const sundaysEnum: keyof typeof DaysOfWeek = "Sundays"; console.log(DaysOfWeek[sundaysEnum]);
Output:
6
Using type assertion
You can also use type assertion to convert a string to an unknown type first and then convert it to an enum type.
Example:
enum DaysOfWeek { Mondays = 0, Tuesdays = 1, Wednesdays = 2, Thursdays = 3, Fridays = 4, Saturdays = 5, Sundays = 6, } const sundays: string = "Sundays"; // Using type assertion to convert string to enum const sundaysEnum = sundays as unknown as DaysOfWeek; console.log(DaysOfWeek[sundaysEnum]);
Output:
6
In the above example, we will declare an enum. Then we declare a variable sundays
of type string. We will do the conversion to an unknown type first using the keyword "as"
, then convert to an enum type.
Summary
To summarise, we already know how to convert a string to enum in TypeScript using some methods like passing a string to an enum object, using "keyof typeof"
, use type assertion, in my opinion, The most common and easiest way is to use type assertion, but you can use any way you want.

Carolyn Hise has three years of software development expertise. Strong familiarity with the following languages is required: Python, Typescript/Nodejs, .Net, Java, C++, and a strong foundation in Object-oriented programming (OOP).