Sub topic 8
How TypeScript Measures Variance on Its Own
Assume you know TypeScript generics, interfaces, function types, structural typing, assignability, and the strict compiler option. This chapter focuses on how TypeScript infers variance from the places where a type parameter appears.
Variance describes how a relationship between type arguments affects a relationship between generic types. TypeScript usually measures this relationship from the structure of a generic declaration instead of requiring you to label every type parameter.
Start with the subtype relationship
class Animal {
name = "animal";
}
class Dog extends Animal {
bark() {
return "woof";
}
}
const dog: Dog = new Dog();
const animal: Animal = dog; // Dog is assignable to AnimalA Dog can be used where an Animal is expected because every Dog has the members required by Animal. The reverse assignment is unsafe because an arbitrary Animal might not have bark().
TypeScript carries this direction through generic types according to how their type parameters are used.
Read the positions where a type appears
The compiler examines whether a type parameter produces values, consumes values, or does both.
| Type parameter use | Example | Inferred behavior |
|---|---|---|
| Output position | `get(): T` | Covariant |
| Input position | `set(value: T)` | Contravariant |
| Input and output | `get(): T` and `set(value: T)` | Invariant |
A producer returns values of type T. If a producer creates Dog values, it is safe to treat it as a producer of Animal values.
interface Producer<T> {
get(): T;
}
const dogProducer: Producer<Dog> = {
get: () => new Dog()
};
const animalProducer: Producer<Animal> = dogProducer;
// Safe: every Dog is an AnimalThe type parameter appears in the return type, so Producer<T> is inferred as covariant in T.
A consumer accepts values of type T. A consumer that can accept any Animal can also accept a Dog, so the assignment direction reverses.
interface Consumer<T> {
accept: (value: T) => void;
}
const animalConsumer: Consumer<Animal> = {
accept: value => console.log(value.name)
};
const dogConsumer: Consumer<Dog> = animalConsumer;
// Safe: dogConsumer accepts a Dog through animalConsumerHere Consumer<T> is inferred as contravariant in T.
Combining positions produces invariance
If a type parameter is both returned and accepted, neither substitution direction is generally safe.
interface Box<T> {
get(): T;
set: (value: T) => void;
}
const dogBox: Box<Dog> = {
get: () => new Dog(),
set: dog => console.log(dog.bark())
};
// Neither Box<Dog> nor Box<Animal> is safely assignable to the other.This makes Box<T> invariant. A mutable box could return a Dog, but it could also receive an Animal that is not a Dog.
Variance can compose
Nested types combine their behavior. A function parameter is contravariant, while a function return type is covariant. Therefore, a type parameter used as a function parameter inside another contravariant position can become covariant overall.
interface HandlerFactory<T> {
create: () => (value: T) => void;
}The outer function returns a handler, so its result is covariant. The handler consumes T, which is contravariant. The two directions cancel, making the overall use of T covariant in this example. With strictFunctionTypes, function-typed properties participate in this analysis.
The compiler follows these positions through members and nested generic types. This is why variance is called emergent: it comes from the declaration's structure.
See the compiler's reasoning
Variance inference helps ordinary assignments, but it does not make mutable structures safe automatically. For example, TypeScript allows some covariant array assignments even though writing through the wider type can be unsafe. Use ReadonlyArray<T> when the API only needs to read values.
Exercise
What variance does interface Store<T> { read(): T; write: (value: T) => void } have, and why?
Show answer
It is invariant because T appears in both an output position (read) and an input position (write).