Unions and Narrowing 28 exercises
solution

Combining Literal & Union Types

The first issue we have is that having the direction as string is much too wide.

In order to restrict what the direction can be, we can use a union type of literal values (in this case strings).

Here's what this looks like:

function move(direction: "up" | "down" | "left" | "ri
Loading solution

Transcript

00:00 Okay, so the way that we do this is instead of having a string, string is way too wide for this situation. Instead, we want to do something like this where we say up or down

00:11 or left or right. Once I finish typing it, let me zoom out so you can see that. Now we have a type here, which is consisted of four members of this union type, each of which is the literal string. You can just put literal strings in here. We could put literal numbers

00:31 in here or literal booleans in here if we wanted as well. But literal strings is what we care about here. So now we have up, down, left and right as the possibilities. And now you could do some logic with up or down or left or right, because we could check if direction

00:45 equals and we get autocomplete on the options here, which is so nice. We also get autocomplete when we're passing in our arguments. So we can move up, we can move right, we can move down. It's just so nice. And of course, we get errors here by saying arguments of type

01:00 upright is not assignable to this parameter. Very, very cool. Now we can, of course, just take this and we can extract to a type alias and we can say direction up here. And now this means that our move function, first of all, the errors get a little bit cleaner actually,

01:18 because instead of having to sort of spill out all of the union types, we actually just say direction, which is really nice. And instead of having it hover over and it show us, you know, up, down, left or right, we just still get direction there. But of course, we still get our beautiful autocomplete. So this is really, really nice. We can capture

01:36 union types and unions of literals in a type and use it later. And we can also do this, also just have it in line. That's perfectly fine too. It doesn't make too much difference. But this is a really nice introduction to literal types. So literal values in TypeScript

01:52 and using them with union types. And this is just fabulous.