Sub topic 3
Declaring contravariance with `in`
Assume you know TypeScript generics, structural typing, assignability, and the strict compiler option. Variance describes how a generic type changes when its type argument changes.
Declaring contravariance with `in`
A consumer accepts values. If an Animal consumer can accept every Dog, it can safely be used where a Dog consumer is expected. This reverses the usual subtype direction, so the type is contravariant.
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
interface Consumer<in T> {
accept(value: T): void;
}
declare const animalConsumer: Consumer<Animal>;
const dogConsumer: Consumer<Dog> = animalConsumer; // OKThe in modifier documents and enforces that T is used as an input. The reverse assignment is rejected because a consumer that accepts only dogs might receive another kind of animal.
Declaring invariance with `in out`
A type that both reads and writes T is invariant. Neither Box<Dog> nor Box<Animal> can substitute for the other.
interface Box<in out T> {
get(): T;
set(value: T): void;
}in out explicitly requires both directions to be checked.
Contradictory annotations
The compiler checks an annotation against the type's structure. This declaration is invalid because out T promises output-only use, but T appears as a function input:
interface Writer<out T> {
write: (value: T) => void; // Error
}A contradiction is a design error, not a request for the compiler to ignore the unsafe use.
When annotations help
Use annotations when they clarify a public API, especially a recursive generic type, or when they help the compiler avoid repeatedly measuring variance in a complex type. They are most valuable when the intended direction is part of the type's design.
Where annotations apply
You can write in, out, or in out on type parameters of generic interfaces, classes, and type aliases. An annotation does not make unrelated types compatible, add runtime checks, or override structural typing. It affects generic assignability checks where TypeScript compares type instantiations.
Exercise
Which annotation belongs on a generic type that only accepts values of T?
Show answer
Use in T, because T appears in an input position.