Errors 10 exercises
solution

Understanding and Fixing 'Type Not Assignable' Errors

Let's investigate a common TypeScript error: "Type is not assignable"


Type 'blue' is not assignable to type 'light' or 'dark'.

This error occurs when we try to pass a value (in this case, 'blue') into a slot that expects one of the types ('light' or 'dark').

Assignability

Loading solution

Transcript

00:00 Okay, let's take a closer look at this error. We can see here that we have type blue is not assignable to type light or dark. You can probably get a sense for what this error means just by looking at it, right? Sure, we're trying to pass blue into a slot expecting light or dark.

00:18 And if we change this to either light or dark, then it's gonna be happy, right? Brilliant. Now, the key word there though is assignable. And that's a really interesting word for this situation because assignability is key to understanding TypeScript as a whole. You might be thinking,

00:36 okay, what are the other ways that we can solve this error? So let's explore assignability through that. Sure, we can solve the error by making sure that the thing we're passing to it is assignable to light or dark. So either light or dark is gonna be good. Or we can actually add blue into the type itself too. So we get light or dark or blue.

00:55 And now blue is assignable to it. It can be passed into that slot because blue is one of the members of the union. Or we can widen theme out even further and make theme into a string here. Now, the only thing that we can't pass to it are things that are not strings, so number. So type number is not assignable to type string.

01:15 So assignable just means can you pass it into that slot or can you not? So you can pass a more specific type into a wider type. So because blue we've got here, sure, we can pass it into this string here because blue is string, even though it's a more specific type of string.

01:34 And if that string is part of, let's say, a member of strings or a union of strings, then that's gonna be fine too. So here light or dark or blue is kind of wider than just blue, but we can just pass in blue itself. Hopefully that makes sense. So assignability just means can I pass this into that slot?

01:53 And the original error that we were looking at here, basically that's what it means. Type blue cannot be passed into a slot expecting light or dark. And so you can use this to kind of understand what assignability means in general. So like when we're looking at more complex errors, you'll often see that this object is not assignable to this object.

02:13 That's what that means. There's some kind of assignability error going wrong there.