Template Literals 7 exercises

Passing Unions Into Template Literals

The challenge was to create a union where its members are 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:

type Sandwich = `${BreadType} sandwich with $

Loading solution


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.