Type Transformations Workshop (6 exercises)

Passing Unions Into Template Literals

The challenge was to create a union where it's members a strings containing all possible permutations of two other unions.

In order to do this, all we need to do is create a template literal and pass in all of the elements as their union types:

Now when we hover over Sandwich, we can see the huge permutation:

Going Further

We can take this concept further.

Inside of the template literal, we can also inline another union:

Keep in mind that this additional union exponentially increases the number of permutations, and with too many added you will eventually hit a limit where the compiler will stop expanding the union.

The big takeaway though is that we're basically just passing a union type into a template literal and it automatically expands it and gives us back a union type.


[0:00] The solution really is this simple. All we do is we create a template literal out of this. Then we pass in all of the elements as their union types. Now, all we have to do is pass in BreadType sandwich with Filling. We end up with this huge, great, big permutation.
[0:19] Now, we can keep going here. We can say you can have a sandwich or a baguette. I can in-line this. I can say sandwich or baguette. Suddenly, I end up with even more of these properties added in. Rye sandwich with cheese, rye baguette with cheese, rye baguette with ham.

[0:36] It keeps going and keeps going. You can keep on adding these, and you will eventually hit a limit. TypeScript will eventually say...I think currently it might be a hundred thousand or ten thousand. I can't quite recall.

[0:48] You will hit a limit in the number of these unions that you can express using this. This is fascinating, because what we're basically doing here is passing a union type into a template literal. It automatically expands it so that you get a union type back out of it. Really useful and fascinating.