Sub topic 11
Covariance, contravariance, and invariance
This chapter assumes you know how assignability works for object types, how functions are compared by parameters and return types, and what a subtype is. Variance describes how a relationship between two types carries over to types built from them, such as functions, arrays, or generic containers.
The question variance answers
Suppose Dog is assignable to Animal. We write that as Dog <: Animal. Now take a type constructor F<T>, such as Array<T>, Promise<T>, or (x: T) => void. Variance answers this question: given Dog <: Animal, what is the relationship between F<Dog> and F<Animal>?
There are four possible answers.
| Variance | Rule | Meaning |
|---|---|---|
| Covariant | `F<Dog>` is assignable to `F<Animal>` | The relationship keeps its direction |
| Contravariant | `F<Animal>` is assignable to `F<Dog>` | The relationship reverses |
| Invariant | Neither direction is assignable | Only the same type fits |
| Bivariant | Either direction is assignable | Direction is ignored |
The position where T appears inside F decides which answer applies.
Covariance: T in output positions
A type is covariant in T when T only appears where values come out, such as return types and readonly properties. A producer of dogs is also a producer of animals, so the direction is preserved.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
declare let getDog: () => Dog;
declare let getAnimal: () => Animal;
getAnimal = getDog; // OK: callers expecting an Animal can use a Dog
getDog = getAnimal; // Error: an Animal has no bark()Return types are covariant. So are Promise<T>, ReadonlyArray<T>, and a readonly property of type T.
Contravariance: T in input positions
A type is contravariant in T when T only appears where values go in, such as function parameters. A function that accepts any Animal can safely be used where a function accepting only Dog is needed, because every Dog is an Animal. The direction reverses.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
declare let handleAnimal: (a: Animal) => void;
declare let handleDog: (d: Dog) => void;
handleDog = handleAnimal; // OK: it can handle any Dog, because a Dog is an Animal
handleAnimal = handleDog; // Error under strictFunctionTypes: it may receive a catThe second assignment fails because a caller of handleAnimal may pass any Animal. handleDog would then call bark() on something that has none.
Invariance: T in both positions
When T appears as both input and output, neither direction is safe. The type is invariant in T.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface Box<T> {
get: () => T;
set: (value: T) => void;
}
declare let dogBox: Box<Dog>;
declare let animalBox: Box<Animal>;
animalBox = dogBox; // Error: set() could store a non-Dog in a Dog box
dogBox = animalBox; // Error: get() could return a non-DogEach direction breaks one of the two members. get demands covariance and set demands contravariance, so the only safe combination is the same type.
How the compiler decides
TypeScript does not store a variance label per type parameter by hand. For a generic type alias, interface, or class, it works the label out by comparing marker instantiations. It checks whether F<Sub> relates to F<Super> and the reverse, using the normal structural rules for the members. It then caches the result and reuses it for later comparisons of F<A> against F<B>, which also keeps recursive types fast.
This has a consequence. The variance of T comes from how T is used in the members, so changing one member can change the variance of the whole type.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface ReadBox<T> {
get: () => T;
}
interface ReadWriteBox<T> {
get: () => T;
set: (value: T) => void;
}
declare let rd: ReadBox<Dog>;
declare let ra: ReadBox<Animal>;
ra = rd; // OK: covariant
declare let wd: ReadWriteBox<Dog>;
declare let wa: ReadWriteBox<Animal>;
wa = wd; // Error: adding set() made T invariantVariance is per type parameter
A type with several parameters has a separate variance for each. In (input: A) => B, the type A is contravariant and B is covariant. Nesting multiplies the effects, in the same way that two negatives make a positive.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
type Callback<T> = (value: T) => void;
type Registrar<T> = (cb: Callback<T>) => void;
declare let regDog: Registrar<Dog>;
declare let regAnimal: Registrar<Animal>;
regAnimal = regDog; // OK: T is covariant in Registrar
regDog = regAnimal; // Error under strictFunctionTypesIn Callback<T>, T is contravariant. Registrar<T> takes a Callback<T> as a parameter, which flips it again, so T is covariant in Registrar<T>. A value of Registrar<Dog> calls its callback with dogs only, so it is safe wherever a registrar of animals is expected, because a callback that handles animals handles dogs.
Where TypeScript bends the rules
Two common features of the language do not follow the strict rules above.
- Methods are bivariant. A parameter declared with method syntax (
handle(a: Animal): void) is compared bivariantly, even understrictFunctionTypes. Only function-typed properties and function type literals get the contravariant check. - Arrays are covariant.
Dog[]is assignable toAnimal[]even thoughpushmakesTappear in an input position. Strictly,Array<T>is invariant.
interface Animal { name: string }
interface Dog extends Animal { bark(): void }
const dogs: Dog[] = [];
const animals: Animal[] = dogs; // OK: allowed for convenience
animals.push({ name: "cat" }); // compiles, but dogs now holds a non-DogBoth choices exist because many real programs rely on them, and rejecting them would break common patterns such as passing a Dog[] to a function that only reads an Animal[]. A later chapter covers the unsound cases in more detail.
Declaring variance explicitly
When the inferred variance is slow to compute or you want a contract that the compiler enforces, annotate the parameter with out (covariant), in (contravariant), or in out (invariant).
interface Producer<out T> {
get(): T;
}
interface Consumer<in T> {
set(value: T): void;
}
interface Box<in out T> {
get(): T;
set(value: T): void;
}If the structure contradicts the annotation, the compiler reports an error. For example, adding set(value: T): void to Producer<out T> is rejected, because T would then appear in an input position. Method syntax is bivariant, so the check is most reliable when you write members as function-typed properties.
Common mistakes
- Expecting
Box<Dog>to be assignable toBox<Animal>when the box is mutable. Check whetherTis also used as an input. - Declaring a callback parameter with method syntax and assuming it is checked contravariantly. Use a function-typed property if you want strict checking.
- Forgetting that
strictFunctionTypesis part ofstrict. Without it, all function parameters are bivariant. - Treating array covariance as a guarantee. It is a deliberate hole, so writes through the wider type can corrupt the narrower array.
Exercise
Given Dog <: Animal, which of these assignments compile under strict? (1) const a: Promise<Animal> = Promise.resolve(dog) where dog: Dog; (2) let f: (x: Dog) => void = (x: Animal) => {}; (3) let g: (x: Animal) => void = (x: Dog) => {}, where the target is a function type literal. Explain each using variance.
Show answer
(1) Compiles. Promise<T> is covariant in T, so Promise<Dog> is assignable to Promise<Animal>. (2) Compiles. Parameters are contravariant, and a function accepting any Animal can handle a Dog. (3) Fails under strictFunctionTypes. The target can be called with any Animal, but the source needs a Dog.
Exercise
An interface Store<T> has value: T (a mutable property) and subscribe(listener: (v: T) => void): void. Is Store<Dog> assignable to Store<Animal>, and which member is the cause?
Show answer
Yes, it compiles under TypeScript's default checking, though it is unsound. Property reads are covariant, but a mutable property is also writable, and TypeScript treats property types covariantly for assignability anyway. The subscribe member is a method, so its parameter is compared bivariantly. Both are deliberate unsound allowances. With in out T and function-typed properties, the compiler would be stricter.