Sub topic 3
Contravariance: types that consume values
This chapter assumes you know TypeScript generics, interfaces, and function types, and that you understand structural assignability. It also assumes you compile with strict enabled. It uses the Animal and Dog classes from the first chapter, where Dog is a subtype of Animal.
The idea in one sentence
A type is contravariant in a type parameter when it only consumes values of that type. A consumer that handles any Animal can safely stand in for a consumer that handles only Dog, so the assignment direction reverses compared with the subtype relationship.
Covariance keeps the direction: Dog to Animal gives Producer<Dog> to Producer<Animal>. Contravariance flips it: Dog to Animal gives Consumer<Animal> to Consumer<Dog>.
A consumer type
A consumer receives values and does something with them. It never hands a T back to its caller. Here is a minimal one, with the in modifier that this tutorial introduces in a later chapter.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Consumer<in T> {
accept(value: T): void;
}
const animalConsumer: Consumer<Animal> = {
accept(a) {
console.log(`Got ${a.name}`);
},
};
// OK: Consumer<Animal> can be used where Consumer<Dog> is required
const dogConsumer: Consumer<Dog> = animalConsumer;
dogConsumer.accept(new Dog());animalConsumer.accept only reads name, which every Animal has. Every Dog is an Animal, so passing a Dog is always safe. The code that holds a Consumer<Dog> promises to send only dogs, and the animal consumer is happy with that promise.
Why the reverse direction fails
Now try the other way around.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Consumer<in T> {
accept(value: T): void;
}
const onlyDogs: Consumer<Dog> = {
accept(d) {
console.log(d.bark());
},
};
// @ts-expect-error: a Consumer<Dog> may call bark(), which a plain Animal lacks
const anyAnimalConsumer: Consumer<Animal> = onlyDogs;
anyAnimalConsumer.accept(new Animal()); // would crash at runtime if allowedCode holding a Consumer<Animal> is allowed to pass any Animal, including one that is not a Dog. onlyDogs calls bark() on its argument, so that call would fail at runtime. The compiler blocks the assignment to prevent this. The @ts-expect-error comment marks the line as an intentional error. If the compiler ever stopped reporting it, the comment itself would become an error.
Where contravariant positions appear
A type parameter is in a contravariant position when values of that type flow into the type from outside. The common cases are:
- Parameters of a function or method.
- Callback types such as
(value: T) => void. - Parameters of a constructor or comparator.
- Setter-like operations that accept
Tbut never return it.
A short summary of the positions you have met so far:
| Position of `T` | Variance | Assignment direction |
|---|---|---|
| Return type, readonly property | Covariant | `Dog` to `Animal` gives `F<Dog>` to `F<Animal>` |
| Function parameter | Contravariant | `Dog` to `Animal` gives `F<Animal>` to `F<Dog>` |
| Both of the above | Invariant | Neither direction |
Contravariance inside function types
Functions are the most common contravariant type you will meet. For function types, a parameter flips the direction and a return type keeps it.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
type Handler<in T> = (value: T) => void;
const handleAnimal: Handler<Animal> = (a) => console.log(a.name);
const handleDog: Handler<Dog> = handleAnimal; // OK
// Combining both directions
declare const makeAnimal: (d: Animal) => Dog;
const makeDog: (d: Dog) => Animal = makeAnimal; // OK
console.log(typeof makeDog);In the second assignment, makeAnimal accepts something wider than a Dog (parameters are contravariant) and returns something narrower than an Animal (return types are covariant). Both changes are safe for a caller who expects (d: Dog) => Animal.
A useful rule: a function is a safe replacement if it requires no more than the original required and promises no less than the original promised.
A practical example: comparators
Sorting is a case where this matters in everyday code. A comparator consumes two values and produces a number.
class Animal {
constructor(public name: string) {}
}
class Dog extends Animal {
bark() {
return "woof";
}
}
type Comparator<in T> = (a: T, b: T) => number;
const byName: Comparator<Animal> = (a, b) => a.name.localeCompare(b.name);
const dogs: Dog[] = [new Dog("Rex"), new Dog("Ace"), new Dog("Max")];
// OK: Comparator<Animal> is assignable to Comparator<Dog>
const byNameForDogs: Comparator<Dog> = byName;
dogs.sort(byNameForDogs);
console.log(dogs.map((d) => d.name).join(", ")); // Ace, Max, RexYou write the comparator once for the general type and reuse it for every subtype. This is why reusable helpers that take a handler, validator, serializer, or event listener for a base type work with specific types.
Strictness decides whether you get contravariance
Contravariance for function parameters is only enforced when strictFunctionTypes is on. It is part of strict. With it off, TypeScript accepts parameters in either direction (bivariance), so the unsafe assignment from Handler<Dog> to Handler<Animal> would compile. With it on, function-typed properties and type aliases are checked contravariantly, as shown above.
This matters in the Consumer interface above. Because accept is declared as a method, the compiler would also accept an assignment in the unsafe direction in some situations, when it compares the members directly. The in annotation tells the compiler to compare Consumer<Animal> and Consumer<Dog> by the declared variance instead, so the error in the onlyDogs example appears. The annotation is therefore a guard as well as documentation.
Common errors
These mistakes appear often when people first work with consumers.
- Assuming the direction follows the subtype. People write
Consumer<Dog>whereConsumer<Animal>is needed, expecting it to work likeProducer<Dog>. AConsumer<Dog>is the narrower, more demanding type, so it cannot replace aConsumer<Animal>. - Reading from a consumer. If a type with
in Talso returnsT, it is no longer purely a consumer. The type is invariant, and the annotation is wrong. The chapter on annotations shows the resulting error. - Forgetting that callbacks nest. A callback parameter inside a parameter flips twice. A type like
(cb: (value: T) => void) => voidusesTin a covariant position, because two contravariant layers cancel out. - Relying on method syntax for safety. Methods are bivariant, so an interface written with methods can hide an unsafe assignment that the function-property form would catch.
Here is the nested-callback case, since it surprises people.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
// T appears inside a callback that is itself a parameter, so it is covariant
type Source<T> = (callback: (value: T) => void) => void;
const dogSource: Source<Dog> = (cb) => cb(new Dog());
// OK: Source<Dog> is assignable to Source<Animal>
const animalSource: Source<Animal> = dogSource;
animalSource((a) => console.log(a.name));The code behind animalSource is a source of dogs. It calls the callback you give it with a Dog, and your callback accepts any Animal, so every call is safe. The type is a producer of T even though T sits in a parameter position.
Checking your understanding
Look at where a type parameter appears and count the flips. Each parameter nesting level flips the direction once. A type parameter that only ever appears in an even number of flips is covariant, and one that only appears in an odd number of flips is contravariant. A parameter that appears in both kinds of position is invariant.
Exercise
Given class Animal {} and class Dog extends Animal { bark() {} }, and type Handler<T> = (value: T) => void, which assignment compiles under strict: const a: Handler<Animal> = dogHandler or const b: Handler<Dog> = animalHandler, where dogHandler: Handler<Dog> and animalHandler: Handler<Animal>? Explain why.
Show answer
Only const b: Handler<Dog> = animalHandler compiles. Handler<T> uses T only as a parameter, so it is contravariant. A handler that accepts any Animal can safely receive a Dog. A handler written for Dog might call bark(), which a general Animal does not have, so dogHandler cannot be used as a Handler<Animal>.
Exercise
Is Source<T> = (callback: (value: T) => void) => void covariant or contravariant in T, and why?
Show answer
Covariant. T appears as a parameter of the callback, which is itself a parameter of Source. Each parameter position flips the direction once, and two flips cancel out. So Source<Dog> is assignable to Source<Animal>.