beraliv

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

Comments

Alexey Berezin profile image

Written by Alexey Berezin who loves London 🏴󠁧󠁢󠁥󠁮󠁧󠁿, players ⏯ and TypeScript 🦺 Follow me on Twitter