DEV Community

AbdlrahmanSaber
AbdlrahmanSaber

Posted on

Convert enum to string literal union type in TS

Hello everyone, this is a quick tutorial, In my work, I wanted to avoid duplicating code as I can and abstract things for example if I use an enum named Weekdays and it contains the following data:

enum Weekdays = {
    MONDAY = 'mon',
    TUESDAY = 'tue',
    WEDNESDAY = 'wed'
}
Enter fullscreen mode Exit fullscreen mode

Let's say you want to create a type called WeekdayType which should contain 'mon' | 'Tue' | 'Wed', how we can do this? Starting from version 4.1 you can do a tricky thing to do it in a single line of code, let's see it.

type WeekdayType = `${Weekdays}`;
// WeekdayType = 'mon' | 'Tue' | 'Wed'|
Enter fullscreen mode Exit fullscreen mode

Congratulations, you did it! Awesome, right?

Top comments (0)