Sub topic 15
Variance annotations with `in` and `out`
Assume you know TypeScript generics, interfaces, and assignability. Variance describes how changing a generic type argument changes the assignability of the complete generic type.
Suppose Dog extends Animal. A generic type is:
- Covariant when
Container<Dog>can be used asContainer<Animal>. - Contravariant when
Handler<Animal>can be used asHandler<Dog>. - Invariant when neither direction is safe.
Declaring output and input positions
Use out for a type parameter that only flows out of a type, such as a return value. Use in for a parameter that only flows into a type, such as a function argument.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface Producer<out T> {
get(): T;
}
interface Consumer<in T> {
consume: (value: T) => void;
}
interface Box<in out T> {
get(): T;
set: (value: T) => void;
}
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer; // OK
declare const animalConsumer: Consumer<Animal>;
const dogConsumer: Consumer<Dog> = animalConsumer; // OK
declare const dogBox: Box<Dog>;
const animalBox: Box<Animal> = dogBox; // ErrorThe producer is safe because every Dog is an Animal. The consumer is safe because something that accepts every Animal can also accept a Dog. The box is unsafe in either direction: reading and writing require the exact same type.
| Annotation | Data flow | Usual relationship |
|---|---|---|
| `out T` | Produces `T` | Covariant |
| `in T` | Consumes `T` | Contravariant |
| `in out T` | Produces and consumes `T` | Invariant |
What annotations do and do not do
TypeScript checks that an annotation agrees with how the type parameter is used. For example, using T as an input in Producer<out T> causes a compiler error. An annotation is a compile-time declaration. It does not change JavaScript output or add runtime checks.
Annotations can make generic comparisons clearer and can help the compiler avoid repeatedly analyzing a complicated type. They do not turn structural typing into nominal typing. Two unrelated types can still be compatible if their structures permit it.
Use annotations when a generic abstraction has an important public variance rule. Do not add them mechanically to every generic type.
Exercise
Why can Consumer<Animal> be assigned to Consumer<Dog>, but Producer<Dog> cannot be assigned to Producer<Animal>?
Show answer
A consumer that accepts every Animal can safely accept a Dog. A producer of Dog cannot safely replace a producer of Animal if callers may expect any Animal.