Making Union out of String in TypeScript

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

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

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

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

That’s it 💫

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

Have a wonderful weekend ☀️

typescriptmedium

Let's chat and have fun 🧑‍💻👩‍💻

No more often than once a week I write 📄 about TypeScript 💪, video playback 📺 and frontend related topics. You can unsubscribe in any time ↘️