Unions and Narrowing 28 exercises
explainer

Literal Type Assignability

This assignability graph is a bit more complex than the last one we looked at:

explanation

Here we have added the individual directions with the possible literal values of "up", "down", "left", and "right". These literals are all able to be assigned to the `"up" | "down" | "left" | "right

Loading explainer

Transcript

00:00 Let's look again at our assignability graph here. We now have a bit more complexity. There's now three levels where we have this up, down, left, right one in the center here. And this is basically consisting of each of these ones down the bottom. So up, down, left, and right.

00:16 And finally, those are also assignable to string. You can think of this in the other way around, of course, string is not assignable to up or down or left and right because it's too wide. And each of these, like up or down or left or right, is not assignable to the ones below it either.

00:34 So you can think of these as kind of, we're getting a sense of like sort of topmost types, like the wider types in TypeScript's ecosystem, and the bottom types are the ones that are lower in the sort of assignability system.

00:47 You can, of course, imagine this too, where if we had a union of, let's say, left or right, then it would be assignable to up or down or left or right because either of those possibilities can merge into that one. So there we go. This is how literals work in terms of thinking about wideness and narrowness in TypeScript types.