DEV Community

AbdlrahmanSaber
AbdlrahmanSaber

Posted on

3

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)

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay