Unions and Narrowing 28 exercises

Diving Deeper into Unions and Assignability

Let's discuss union types and assignability in a bit more detail.

Consider this graph:


At the top, we have string | number. This means it could either receive a string or a number.

However, you can't pass string | number into a function that's just expecting a string.


Loading explainer


00:00 Diving into unions a little bit more, I want to introduce this graph, which was going to come up a lot when we talk about unions and assignability, you can think that imagine if we have a type like at the top here where we have string or number there, string or number, it could either receive string or it could receive number. But if you think about it, you can't pass string or number into a function that's just expecting string.

00:25 So this idea of being able to assign, you can assign string to string or number, you can assign number to string or number, but you can't go the other way around is really important in TypeScript.

00:35 And as we work through these exercises, I'm going to expand out this graph with all of the types that belong in TypeScript so we can see, get a sense for the shape of how TypeScript understands assignability. Very important.