Understand assignability in TypeScript

This piece of code might look completely confusing to you.


type Name = string
type GoodName = VeryGoodName | "fred"
type VeryGoodName = "matt"
const isGoodName = (name: GoodName) => {}
isGoodName("matt")
export type Result = Name extends GoodName ? true : false

Name extends GoodName, if it does, return true, if it doesn't, return false. What, okay, and you'd expect name,

Now you'd think this would return true right? Name is a string, VeryGoodName is the string "matt" and GoodName is a union between VeryGoodName and "fred". All strings.

So it'd make sense for Name extends GoodName to be true, but it's not. It's actually false. That's interesting!

To understand this, we need to understand assignability.


class Animal {
isAnimal() {
return true
}
}
class Dog extends Anigal {
isDog() {
return true
}
}
class Labrador extends Dog {
isLabrador() {
return true
}
}

Here we have kind of like the traditional object oriented classes thing. And we can take our 'thing' for a walk. We can say that we can take any dog for a walk, but Animal is not assignable to dog.


const takeForWalk = (dog: Dog) => {}
takeForWalk(new Animal()) // error

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. The reason for that 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. So you can take your Labrador for a walk because it's a narrow version of a Dog. It's still a Dog, right?.

And so we can look back on our Result type and see that what we are really checking here with the extends is if Name is a narrower version of GoodName. And it's not.


type Name = string
type GoodName = VeryGoodName | "fred"
type VeryGoodName = "matt"
const isGoodName = (name: GoodName) => {}
isGoodName("matt")
export type Result = Name extends GoodName ? true : false // false

And so we can acually swap them and it will be true since GoodName is the narrower version of Name.


export type Result = GoodName extends Name ? true : false // true

VeryGoodName is also a narrower version of name, and it's also a narrower version of GoodName, because it's part of that union too.


export type Result1 = VeryGoodName extends Name ? true : false // true
export type Result2 = VeryGoodName extends GoodName ? true : false // true

That should give you a good idea about what assignability means, and about what this extends keyword is doing in this conditional check.

Transcript

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: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:40 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: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.

1:13 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.

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.

1:47 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.


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

More Tips

Play Type Predicates

Type Predicates

1 min

Play TypeScript 5.1 Beta is OUT!

TypeScript 5.1 Beta is OUT!

2 mins

Play How to Name your Types

How to Name your Types

4 mins

Play Don't use return types, unless...

Don't use return types, unless...

4 mins

Play TypeScript 5.0 Beta Deep Dive

TypeScript 5.0 Beta Deep Dive

6 mins

Play Conform a Derived Type Without Losing Its Literal Values

Conform a Derived Type Without Losing Its Literal Values

1 min

Play Avoid unexpected behavior of React’s useState

Avoid unexpected behavior of React’s useState

1 min

Play Compare function overloads and generics

Compare function overloads and generics

1 min

Play Use infer in combination with string literals to manipulate keys of objects

Use infer in combination with string literals to manipulate keys of objects

1 min

Play Access deeper parts of objects and arrays

Access deeper parts of objects and arrays

1 min

Play Ensure that all call sites must be given value

Ensure that all call sites must be given value

1 min

Play Understand how TypeScript infers literal types

Understand how TypeScript infers literal types

1 min

Play Get a TypeScript package ready for release to NPM in under 2 minutes

Get a TypeScript package ready for release to NPM in under 2 minutes

1 min

Play Use assertion functions inside classes

Use assertion functions inside classes

1 min

Play Assign local variables to default generic slots to dry up your code and improve performance

Assign local variables to default generic slots to dry up your code and improve performance

2 mins

Play Know when to use generics

Know when to use generics

2 mins

Play Map over a union type

Map over a union type

1 min

Play Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

1 min

Play Use generics to dynamically specify the number, and type, of arguments to functions

Use generics to dynamically specify the number, and type, of arguments to functions

1 min

Play Use 'declare global' to allow types to cross module boundaries

Use 'declare global' to allow types to cross module boundaries

2 mins

Play Turn a module into a type

Turn a module into a type

2 mins

Play Create autocomplete helper which allows for arbitrary values

Create autocomplete helper which allows for arbitrary values

2 mins

Play Use deep partials to help with mocking an entity

Use deep partials to help with mocking an entity

1 min

Play Throw detailed error messages for type checks

Throw detailed error messages for type checks

1 min

Play Create a 'key remover' function which can process any generic object

Create a 'key remover' function which can process any generic object

1 min

Play Use generics in React to make dynamic and flexible components

Use generics in React to make dynamic and flexible components

1 min

Play Create your own 'objectKeys' function using generics and the 'keyof' operator

Create your own 'objectKeys' function using generics and the 'keyof' operator

1 min

Play Write your own 'PropsFrom' helper to extract props from any React component

Write your own 'PropsFrom' helper to extract props from any React component

1 min

Play Use 'extends' keyword to narrow the value of a generic

Use 'extends' keyword to narrow the value of a generic

1 min

Play Use function overloads and generics to type a compose function

Use function overloads and generics to type a compose function

2 mins

Play Decode URL search params at the type level with ts-toolbelt

Decode URL search params at the type level with ts-toolbelt

2 mins

Play Use 'in' operator to transform a union to another union

Use 'in' operator to transform a union to another union

2 mins

Play Derive a union type from an object

Derive a union type from an object

2 mins