Designing Your Types 11 exercises

Passing Unions to Template Literal Types

When you pass a union type to a template literal, it expands.

Following the pattern of the tests, we can see that the desired results are named:

bread "sandwich with" filling

That means we should pass the BreadType and Filling unions to the Sandwich template literal with the str

Loading solution


00:00 Okay, the key lesson with this is that when you pass a union to a template literal type, it basically like expands. So let's say we have, okay, we need bread type and we need filling. So we can start to see that we need to pass bread type into this sandwich.

00:16 And so we can add something to the template literal type, we can say sandwich like that. And we get rye brown and white sandwiches. But what happens if we also pass in the filling? So let's say, and we say filling inside here, you might think that we'd end up with sort

00:33 of, I don't know, some sort of strange combination, or it wouldn't sort of expand out as you like might imagine. But what we get is we get rye sandwich cheese, rye sandwich ham, rye sandwich salami, we get all the possible like setups for this. And so what you get if you add another bread type, then it's going to go even further.

00:52 And then you get so many more like 20 more here. Rye sandwich cheese rye, rye sandwich cheese brown, rye sandwich cheese white, rye sandwich ham rye, rye sandwich ham brown. Isn't this crazy? And so to fulfill this, we just need to say with filling. Look at that. And so you get this amazing, amazing just spreading of all of the things that you add

01:12 in to a template literal. You can go further with this as well. You can say like, let's say this is 20 bucks. And so this will actually put in into the template literal. So it will sort of be stringified there. Let's say it's 20 bucks and let's maybe add a dollar sign or maybe it's 40 bucks here.

01:31 Now you've got 20 on some and you've got 40 on others. I mean, this is just such powerful stuff. And like being able to just build out unions very quickly from this. It's a power that you need to use sometimes, but quite rarely.

01:48 And mostly I'm showing it to you because it's pretty fun being able to build this stuff. And when you see in the future, oh yes, I've got a use case for this. You'll remember the bread type and the filling and how they go together.