Sub topic 11
Covariance, contravariance, and invariance
This chapter assumes basic TypeScript syntax, interfaces, functions, arrays, and compiler errors. It also assumes strict mode, which enables stricter function checks.
Variance describes type relationships
Variance describes how a generic or compound type changes when its type parameter changes.
Assume Dog extends Animal. Every Dog is an Animal, but not every Animal is a Dog.
| Variance | Relationship | Example |
|---|---|---|
| Covariance | `Container<Dog>` can become `Container<Animal>` | A read-only producer |
| Contravariance | `Consumer<Animal>` can become `Consumer<Dog>` | A function that accepts values |
| Invariance | Neither direction is safe | A mutable reader and writer |
The source is the value or type on the right side of an assignment. The target is the type on the left side.
Covariance: safe reading
A covariant type produces values. If a producer returns a Dog, code expecting an Animal can use it because every Dog has the Animal properties.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface Producer<T> {
get(): T;
}
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer;
const animal = animalProducer.get();
console.log(animal.name);The assignment is safe because callers of animalProducer only expect an Animal. They do not need to call bark.
Return types are therefore checked covariantly. A function returning Dog can be used where a function returning Animal is required.
Contravariance: safe accepting
A contravariant type consumes values. A consumer that can handle every Animal can also handle a Dog.
const animalHandler = (animal: Animal): void => {
console.log(animal.name);
};
const dogHandler: (dog: Dog) => void = animalHandler;
// Unsafe: this handler requires bark(), so it cannot handle every Animal.
// const animalHandler2: (animal: Animal) => void = dogHandler;The second assignment would be unsafe. The caller could pass an Animal that is not a Dog, then dogHandler could try to call bark.
Function parameters are checked in the opposite direction from return values. A function that accepts fewer requirements is more reusable.
Invariance: safe reading and writing
A mutable type both produces and consumes its type parameter. Neither covariance nor contravariance alone is safe.
interface Box<T> {
get: () => T;
set: (value: T) => void;
}
declare const dogBox: Box<Dog>;
// Neither assignment is safe under strict function checking.
// const animalBox: Box<Animal> = dogBox;
// const anotherDogBox: Box<Dog> = {} as Box<Animal>;If a Box<Dog> became a Box<Animal>, someone could write a non-Dog animal into it. Later, code reading from the original box would expect a Dog and fail.
TypeScript’s practical exceptions
TypeScript intentionally permits some unsound relationships for compatibility. Mutable arrays are treated as covariant:
const dogs: Dog[] = [];
const animals: Animal[] = dogs;
animals.push({ name: "Mittens" });The compiler accepts the assignment, even though dogs now contains a non-Dog value. Prefer readonly Dog[] when a function only needs to read values.
With strictFunctionTypes, function-typed properties use safer parameter checking. Method syntax remains more permissive for historical reasons. Use function properties when you want strict variance behavior.
Exercise
Why can a Producer<Dog> become a Producer<Animal>, but a mutable Box<Dog> cannot become a Box<Animal>?
Show answer
A producer only returns values, so every Dog satisfies the Animal contract. A mutable box also accepts values, and a caller could write a non-Dog Animal into a Box<Dog>.