Last updated: Feb 26, 2024
Reading timeยท2 min
To convert a string to an enum:
keyof typeof
to cast the string to the type of the enum.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.
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.
enum EmailStatus { Read, Unread, Draft, } // โ๏ธ Error: Type "Test" is not assignable to type "Read" | "Unread" | "Draft" const str: keyof typeof EmailStatus = 'Test'; console.log(EmailStatus[str]); // ๐๏ธ undefined
You can access the value that corresponds to the string in the enum by using bracket notation.
enum EmailStatus { Read, Unread, Draft, } const str: keyof typeof EmailStatus = 'Read'; console.log(EmailStatus[str]); // ๐๏ธ 0
An alternative approach is to assert that the variable that stores the string
has a type of Enum
.
enum EmailStatus { Read, Unread, Draft, } const str = 'Read'; const strEnum = str as unknown as EmailStatus; console.log(EmailStatus[strEnum]); // ๐๏ธ 0
We used a type assertion to specify that the str
variable stores a value that
has a type of EmailStatus
.
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.
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
.
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've also written an article on how to convert an enum to a string.
If you need to check if a value exists in an enum, click on the following article.
You can learn more about the related topics by checking out the following tutorials: