Understand assignability in TypeScript

export type Result = string extends "matt" ? true : false;

I always find these conditional types SUPER hard to read. If you think Result is true, you might need a better mental model for assignability in TypeScript.

Discuss on Twitter

Transcript

[0:00] [0: 00] This piece of code might look completely confusing to you. Name extends GoodName. If it does, return true. If it doesn't, return . You'd expect Name is a string up here. GoodName is either VeryGoodName or Fred here. The VeryGoodName is Matt. This is a string union. It should be related to string, so this should be returning true, right? No, it returns . That's interesting.
[0:00]

[0:26] [0: 26] To understand this, we need to understand assignability. We're going to go back a little bit to do that. Here, we've got an Animal, we've got a Dog which extends Animal, and we got a Labrador which extends Dog. Here, that's like the traditional object-oriented classes thing.

[0:00]

[0:40] [0: 41] We can take our thing for a walk. We can say, "OK, we can take any dog for a walk," but Animal is not assignable to Dog. We can take our Labrador for a walk, that's absolutely fine. We can take our Dog for a walk, but we can't take our Animal for a walk. We can't take our goldfish for a walk.

[0:00]

[0:58] [0: 58] The reason for that is the animal, even though a dog is an animal, an animal is a wider version of that, whereas a Labrador is a narrower version of a dog. You can take your Labrador for a walk because it's a narrow version of a dog. It's still a dog.

[0:00]

[1:13] [1: 15] We can look back on this and think Name extends GoodName. What we're checking here is, is Name a narrower version of GoodName, just like an animal is a dog is a narrower version of an animal? We notice that we can actually swap these guys over.

[0:00]

[1:33] [1: 33] GoodName extends Name, and it will return true because GoodName is a narrower version of Name. VeryGoodName is also a narrower version of Name and it's a narrower version of GoodName as well because it's part of that union, too.

[0:00]

[1:47] [1: 48] We get the same thing in this isGoodName thing here, where we can pass in either Fred or Matt. If we change this to VeryGoodName, then it's still going to work but we can't pass in Fred anymore. That should give you a good idea about what assignability means and about what this extends keyword is doing in this conditional check.

[0:00]

More Tips