Transform string literal type into union of characters in TypeScript

Example of StringToUnion use
Example of StringToUnion use

Today we discuss StringToUnion

Type transformations are useful for different types of tasks.

We already discussed:

Let's go 🚀

Iteration over a string

Let's start from the first character:

Get first character, version 1
Get first character, version 1

We cannot extract it using indices as we get string. Instead let's apply Type inference in conditional types:

Get first character, version 2
Get first character, version 2

Putting characters into a union

Next step is to put other characters into a union.

As we already can get first character, let's apply it recursively:

Final solution
Final solution

On the final step where we have an empty string, it converts to never

If we deal with a union type, never is the type when we have no elements in it. But if we put any element in it, never will be removed from it:

Never in a union type
Never in a union type

That's it 💫

Don't forget to check the final solution on Playground – https://tsplay.dev/N7bXqw

Have a wonderful weekend ☀️

typescript

Alexey Berezin

Senior Software Engineer, UK Global Talent 🇬🇧

The portrait photo of me

Thank you for reading my blog post! If you have any questions, suggestions, or just want to say hi, feel free to reach out in social networks, or via email. I would love to hear from you!

Comments