Convert a String to Enum in TypeScript

avatar

Borislav Hadzhiev

Last updated: Feb 13, 2022

banner

Photo from Unsplash

Convert a String to Enum in TypeScript #

To convert a string to an enum:

  1. Use keyof typeof to cast the string to the type of the enum.
  2. Use bracket notation to access the corresponding value of the string in the enum.
index.tsx
enum EmailStatus { Read, Unread, Draft, } // 👇️ String to enum const str: keyof typeof EmailStatus = 'Read'; console.log(EmailStatus[str]); // 👉️ 0 const enumToStr = EmailStatus[EmailStatus.Read]; console.log(enumToStr); // 👉️ "Read"

Using keyof typeof allows us to get a type that represents all Enum keys as strings.

index.tsx
enum EmailStatus { Read, Unread, Draft, } // 👇️ type T = "Read" | "Unread" | "Draft" type T = keyof typeof EmailStatus;

If we set the type of the string to one of the possible types of the enum, we would get an error if there is a mismatch.

index.tsx
enum EmailStatus { Read, Unread, Draft, } // ⛔️ Error: Type "Test" is not assignable to type "Read" | "Unread" | "Draft" const str2: keyof typeof EmailStatus = 'Test'; console.log(EmailStatus[str2]); // 👉️ undefined

You can access the value that corresponds to the string in the enum by using bracket notation.

index.tsx
enum EmailStatus { Read, Unread, Draft, } // // ⛔️ Error: Type "Test" is not assignable to type "Read" | "Unread" | "Draft" const str2: keyof typeof EmailStatus = 'Read'; console.log(EmailStatus[str2]); // 👉️ 0

An alternative approach is to assert that the variable that stores the string has a type of Enum.

index.tsx
enum EmailStatus { Read, Unread, Draft, } const str = 'Read'; const strEnum = str as unknown as EmailStatus; console.log(EmailStatus[strEnum]); // 👉️ 0

In the example above, we assert that the str variable stores a value that has a type of EmailStatus.

This approach is not as clean as using keyof typeof and should be avoided when possible because it doesn't defend against incorrect values.

You could cast any string to have a value of EmailStatus without getting an error.

index.tsx
enum EmailStatus { Read, Unread, Draft, } const str = 'Test'; const strEnum = str as unknown as EmailStatus; console.log(EmailStatus[strEnum]); // 👉️ undefined

This is not the case when using keyof typeof.

index.tsx
enum EmailStatus { Read, Unread, Draft, } // ⛔️ Error: Type "Test" is not assignable to type "Read" | "Unread" | "Draft" const str: keyof typeof EmailStatus = 'Test';

TypeScript is smart enough to notice that Test is not one of the keys in the enum and shows an error when a typo is made.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.