Sub topic 3
Contravariance: types that consume values
This chapter assumes you understand TypeScript generics, interfaces, function types, structural typing, and the strict compiler option. Contravariance matters when a generic type consumes values instead of producing them.
A type parameter is in an input position when a value enters through it. Function parameters are common input positions. A type that consumes T is often contravariant in T.
The assignment direction reverses
Start with a subtype relationship:
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dog: Dog = new Dog();
const animal: Animal = dog; // OK: every Dog is an AnimalA Dog can be used where an Animal is expected because a dog has all the members required by Animal.
Now consider a consumer. A consumer accepts values but does not return them:
type Consumer<T> = (value: T) => void;
const animalConsumer: Consumer<Animal> = (value) => {
console.log(value.name);
};
const dogConsumer: Consumer<Dog> = animalConsumer;
dogConsumer(new Dog()); // OKThe assignment works because animalConsumer can accept every Dog. A Dog is an Animal, and the consumer only needs the name member that every Animal has.
The direction is reversed:
| Assignment | Result | Reason |
|---|---|---|
| `Consumer<Animal>` to `Consumer<Dog>` | Allowed | A consumer of every animal can consume a dog |
| `Consumer<Dog>` to `Consumer<Animal>` | Rejected | A dog-only consumer cannot safely consume every animal |
flowchart TD
A["Dog is a subtype of Animal"] --> B["Consumer<Animal> can accept any Dog"]
B --> C["Consumer<Animal> is assignable to Consumer<Dog>"]
C --> D["The type argument direction is reversed"]Why the reverse assignment is unsafe
Suppose TypeScript allowed a dog-only consumer to become an animal consumer:
type Consumer<T> = (value: T) => void;
const onlyDogs: Consumer<Dog> = (dog) => {
console.log(dog.bark());
};
// const acceptsAnyAnimal: Consumer<Animal> = onlyDogs;
// acceptsAnyAnimal(new Animal()); // Animal has no bark()The commented assignment would be unsafe. The resulting variable promises to accept any Animal, but the actual function requires a Dog. An Animal might be a cat, bird, or another subclass without bark().
This is why function parameter types are checked contravariantly when strictFunctionTypes is enabled.
Declaring contravariance with `in`
TypeScript 4.7 introduced variance annotations. The in modifier documents that a type parameter is used as an input:
interface Consumer<in T> {
accept(value: T): void;
}
const animalConsumer: Consumer<Animal> = {
accept(value) {
console.log(value.name);
},
};
const dogConsumer: Consumer<Dog> = animalConsumer;
dogConsumer.accept(new Dog());The annotation communicates the intended relationship to readers and allows the compiler to check that the declaration agrees with its structure. If T appears in an output position, the annotation contradicts the design.
For example:
interface BadConsumer<in T> {
accept(value: T): void;
// get(): T; // Error: T would also be used as output
}A type that both consumes and produces a value generally needs invariance, discussed in the next chapter.
Exercise
Why is Consumer<Animal> assignable to Consumer<Dog>, but Consumer<Dog> is not assignable to Consumer<Animal>?
Show answer
Every Dog is an Animal, so a consumer that handles every Animal can handle a Dog. A consumer that handles only Dogs cannot promise to handle every Animal.