Sub topic 10
Declaring Contravariance with `in`
This chapter assumes that you understand TypeScript generics, interfaces, function types, structural typing, assignability, and the strict compiler option. Variance describes how a relationship between types such as Dog and Animal affects a generic type such as Consumer<Dog>.
Contravariance applies to types that consume values. A consumer accepts a value, stores it, or uses it as an input. TypeScript 4.7 added the in modifier for declaring this relationship explicitly.
The assignment direction
Assume that Dog is a subtype of Animal. Every dog is an animal, so a value of type Dog can be used where an Animal is expected.
A consumer reverses this direction:
| Assignment | Allowed? | Reason |
|---|---|---|
| `Consumer<Animal>` to `Consumer<Dog>` | Yes | An animal consumer can accept every dog |
| `Consumer<Dog>` to `Consumer<Animal>` | No | It might receive a cat or another animal |
A Consumer<Dog> promises to handle dogs only. It cannot safely receive an arbitrary animal. A Consumer<Animal> can handle dogs because dogs are animals.
Writing a contravariant interface
Use in T when the type parameter appears only in input positions. In this example, T is the parameter type of a function property.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Consumer<in T> {
accept: (value: T) => void;
}
const animalConsumer: Consumer<Animal> = {
accept: (animal) => {
console.log(animal.name);
},
};
const dogConsumer: Consumer<Dog> = animalConsumer;
dogConsumer.accept(new Dog()); // Safe: every Dog is an Animal
// This direction is unsafe and rejected:
// const animalConsumer2: Consumer<Animal> = dogConsumer;The dogConsumer variable can refer to animalConsumer because the caller is allowed to provide only a Dog. The animalConsumer implementation can accept that value.
If the reverse assignment were allowed, the caller could pass a different kind of animal:
class Cat extends Animal {}
declare const onlyDogs: Consumer<Dog>;
// Rejected: onlyDogs might not know how to accept a Cat.
// const anyAnimal: Consumer<Animal> = onlyDogs;
// anyAnimal.accept(new Cat());The type system prevents this unsafe call.
Why the modifier matters
Without an annotation, TypeScript can usually infer variance by examining the structure of a generic type. The in modifier makes the intended direction explicit:
flowchart TD
A["Consumer<Animal>"] -->|"assignable to"| B["Consumer<Dog>"]
B -->|"not assignable to"| A
C["A consumer accepts input"] --> A
C --> BThe modifier also checks that the declaration matches its claim. A type parameter marked in must not be used as an output:
// Error: T is marked "in" but is returned as output.
// interface Invalid<in T> {
// get(): T;
// }If a type both accepts and returns T, it needs a different variance classification. Such a type is generally invariant, so neither Box<Dog> nor Box<Animal> can safely replace the other.
Function parameters and strictness
For function-typed properties, strictFunctionTypes checks parameter types contravariantly. The strict compiler option enables this check.
This rule protects callers. A callback that handles every Animal can be used where a callback for Dog is required. A callback that handles only Dog cannot be used where a callback for every Animal is required.
Use in when the generic abstraction is intentionally a consumer, such as an event handler, validator, visitor, or command processor. The annotation communicates the safe assignment direction to readers and to the compiler.
Exercise
Why is Consumer<Animal> assignable to Consumer<Dog>, but Consumer<Dog> is not assignable to Consumer<Animal>?
Show answer
A consumer of Animal can accept every Dog. A consumer of Dog may reject another Animal, such as a Cat.