Sub topic 1
Subtyping and Assignability: Dog and Animal
Variance is about how a relationship between two types carries over to generic types built from them. Before that, you need a firm grasp of the underlying relationship: when TypeScript lets you use a value of one type where another type is expected. This chapter sets up that relationship with the Animal and Dog pair that the rest of the tutorial reuses.
Prerequisites
This chapter assumes you already know the following:
- Type parameters on interfaces, classes, and type aliases (generics).
- Basic interfaces, classes, and function types.
- The idea of structural typing, where compatibility depends on shape and not on declared names.
- How to turn on the
strictcompiler option intsconfig.json.
You do not need to know anything about variance yet.
What a subtype is
A type S is a subtype of a type T when every value of type S can safely be used wherever a T is expected. In that case T is the supertype. "Safely" means that any operation the code performs on a T also works on the S.
Here is the pair used throughout this tutorial:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dog: Dog = new Dog();
const animal: Animal = dog; // OK: Dog is a subtype of Animal
// const backToDog: Dog = animal; // Error: Animal lacks bark()
console.log(animal.name); // "animal"A Dog has everything an Animal has (name) plus more (bark). Code written against Animal only touches name, so handing it a Dog is safe. The reverse fails, because code written against Dog may call bark(), and a plain Animal has no such method.
The rule to remember: a subtype has at least the capabilities of its supertype. The subtype can stand in for the supertype, and the supertype cannot stand in for the subtype.
Assignability is checked structurally
TypeScript does not require extends to establish a subtype relationship. It compares shapes. Any type with a compatible name property is usable as an Animal:
class Animal {
name = "animal";
}
class Cat {
name = "cat";
meow() {
return "meow";
}
}
const pet: Animal = new Cat(); // OK: Cat has everything Animal requires
const wolf = { name: "wolf", howl: () => "awoo" };
const wild: Animal = wolf; // OK: the object's shape is compatible
console.log(pet.name, wild.name);Cat never mentions Animal, yet it is assignable to it. The same holds for the plain object wolf.
Two details can surprise you:
- Private and protected members make a class nominal. If
Animaldeclared aprivatefield, onlyAnimaland its subclasses would be assignable to it. A class that happens to have the same field name would be rejected, because the private member must originate in the same declaration. - Fresh object literals get an extra check. Writing an object literal directly where
Animalis expected triggers an excess property check. Assigning the same object through a variable does not.
class Animal {
name = "animal";
}
// const a: Animal = { name: "wolf", howl: () => "awoo" };
// Error: object literal may only specify known properties; 'howl' does not exist in type 'Animal'
const wolf = { name: "wolf", howl: () => "awoo" };
const b: Animal = wolf; // OK: not a fresh literal, so no excess property check
console.log(b.name);The excess property check is a guard against typos. It is not part of the subtype relationship itself.
Subtyping versus assignability
The compiler uses two closely related relations:
- The subtype relation is the strict one described above.
- The assignability relation is slightly more permissive. It is the one that decides whether
const x: T = valuecompiles.
Assignability allows a few conveniences that a strict subtype relation would not:
anyis assignable to every type, and every type is assignable toany.- A number-typed value is assignable to a numeric enum type.
- An object without an optional property is assignable to a type that declares it.
For the Dog and Animal examples in this tutorial the two relations agree. When this tutorial says "assignable", it means "the compiler accepts the assignment". When it says "subtype", it means the underlying safe-substitution idea.
Where subtyping shows up
Subtyping is not limited to classes. You already rely on it in several places:
| Situation | Subtype | Supertype | Column |
|---|---|---|---|
| Literal types | `"woof"` | `string` | |
| Union members | `Dog` | `Dog \ | Cat` |
| Extended interfaces | `interface Puppy extends Dog` | `Dog` | |
| Everything | any type | `unknown` | |
| Nothing at all | `never` | any type |
A few of these in code:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const sound: string = "woof" as const; // "woof" is a subtype of string
const maybeDog: Dog | undefined = new Dog(); // Dog is a subtype of Dog | undefined
const anything: unknown = new Dog(); // everything is a subtype of unknown
function describe(a: Animal): string {
return `I am ${a.name}`;
}
console.log(describe(new Dog()), sound, maybeDog.bark(), anything);Passing a Dog to describe works for the same reason as the earlier assignment. Parameter passing is just assignment of the argument to the parameter.
Going down: narrowing instead of assigning
Sometimes you hold an Animal and you know, or want to find out, that it is a Dog. You cannot assign down. You can check, and the compiler then narrows the type:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
function speak(animal: Animal): string {
if (animal instanceof Dog) {
return animal.bark(); // narrowed to Dog inside this branch
}
return "...";
}
console.log(speak(new Dog()), speak(new Animal()));A type assertion (animal as Dog) also compiles, but it only silences the compiler. If the value is not actually a Dog, calling bark() fails at runtime. Prefer narrowing when you can.
Subtyping between generic types
Now the question this tutorial answers. If Dog is a subtype of Animal, what is the relationship between Box<Dog> and Box<Animal>, or between () => Dog and () => Animal, or between (a: Dog) => void and (a: Animal) => void?
The relationship between the element types does not automatically decide the relationship between the generic types. Each of those examples answers differently. One glimpse, with function types:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const makeDog = (): Dog => new Dog();
const makeAnimal: () => Animal = makeDog; // OK: returning a Dog is fine where an Animal is promised
const feedAnimal = (a: Animal): void => console.log(a.name);
const feedDog: (d: Dog) => void = feedAnimal; // OK: a function that accepts any Animal accepts a Dog
// const makeDog2: () => Dog = makeAnimal; // Error: Animal is not a Dog
// const feedAnimal2: (a: Animal) => void = (d: Dog) => d.bark(); // Error under strictFunctionTypes
console.log(makeAnimal().name);
feedDog(new Dog());Look at the direction in each case. For the return type, Dog to Animal goes the same way as the element types. For the parameter type, the direction flips: a function taking Animal is usable as a function taking Dog. These two behaviors are covariance and contravariance, and the next chapters define them properly.
Common mistakes at this stage
- Assuming
extendsis required. Shape decides compatibility. A class that never extendsAnimalcan still be anAnimalfor the compiler. - Reading the arrow backwards. "Dog is assignable to Animal" means a
Doggoes into anAnimalslot. People often invert it becauseAnimalfeels like the bigger type. The subtype has more members, and the supertype has fewer. - Using
asto go down. An assertion removes the compiler's check without adding a runtime one. - Assuming generics follow element types. Do not assume
Box<Dog>is assignable toBox<Animal>just becauseDogis assignable toAnimal. Whether it holds depends on howTis used insideBox.
Summary
A subtype can be used wherever its supertype is expected. TypeScript decides this from structure, with extra rules for private members and fresh object literals. Assignment goes up from Dog to Animal, and going down needs narrowing. Whether this direction survives wrapping the types in a generic, such as Producer<Dog> or Consumer<Dog>, is the question variance answers.
Exercise
Given class Animal { name = "animal"; } and class Cat { name = "cat"; meow() { return "meow"; } }, where Cat does not extend Animal, does const a: Animal = new Cat(); compile? Does const c: Cat = new Animal(); compile? Explain both results using the idea of a subtype.
Show answer
The first line compiles. TypeScript checks structure, and Cat has the name property that Animal requires, so Cat is a subtype of Animal even without extends. The second line does not compile, because Animal lacks meow(). A supertype cannot stand in for a subtype that has extra members.
Exercise
A class Animal declares private id = 1;. A separate class Robot also declares private id = 1; and name = "robot". Is Robot assignable to Animal? Why or why not?
Show answer
No. Private members make a class compare nominally. The private id in Robot does not come from the same declaration as the one in Animal, so Robot is not assignable to Animal, even though the names and types match.