Sub topic 15
Variance in Generic Types
This chapter assumes you know generic interfaces, type aliases, and classes, and the extends relationship between interfaces. It also assumes you compile with strict: true, which turns on strictFunctionTypes. Several results below depend on that flag.
What Variance Describes
Subtyping asks whether one type can stand in for another. Dog is a subtype of Animal if every Dog has everything an Animal has. A value of the subtype can go wherever the supertype is expected.
Variance asks a follow-up question about generic types. If Dog is assignable to Animal, is Box<Dog> assignable to Box<Animal>? The answer depends on how Box uses T. There are four possible answers:
- Covariant:
Box<Dog>is assignable toBox<Animal>. The direction is the same as forDogandAnimal. - Contravariant:
Box<Animal>is assignable toBox<Dog>. The direction is reversed. - Invariant: neither direction is allowed.
- Bivariant: both directions are allowed. This is rarely what you want, and it appears in TypeScript mostly for historical reasons.
TypeScript works variance out for you by comparing structures. You never declare it in everyday code. Knowing the rules explains many assignability errors that otherwise look arbitrary.
The Running Example
The examples below use these two types:
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
const dog: Dog = {
name: "Rex",
bark() {
console.log("Woof");
},
};Covariance: Types That Produce T
When T appears only in output positions, such as return types and read-only properties, the generic type is covariant.
type Producer<T> = () => T;
const makeDog: Producer<Dog> = () => dog;
const makeAnimal: Producer<Animal> = makeDog; // OKThis is safe because anyone calling makeAnimal() expects an Animal. A Dog satisfies that expectation. Going the other way is an error, because a caller of Producer<Dog> may call .bark(), and a plain Animal has no such method.
Contravariance: Types That Consume T
When T appears only in input positions, such as function parameters, the direction reverses.
type Consumer<T> = (value: T) => void;
const printName: Consumer<Animal> = (a) => console.log(a.name);
const handleDog: Consumer<Dog> = printName; // OK
// const barker: Consumer<Dog> = (d) => d.bark();
// const handleAnimal: Consumer<Animal> = barker;
// Error: Type 'Consumer<Dog>' is not assignable to 'Consumer<Animal>'A function that can handle any Animal can certainly handle a Dog. A function that requires a Dog cannot be trusted with an arbitrary Animal, because it may call .bark() on a cat. The more general parameter type is the safer one, so a consumer of a supertype stands in for a consumer of a subtype.
Invariance: Types That Both Read and Write T
If T appears in both an input and an output position, neither direction is safe, and the type is invariant.
interface Cell<T> {
get: () => T;
set: (value: T) => void;
}
declare const dogCell: Cell<Dog>;
declare const animalCell: Cell<Animal>;
// const a: Cell<Animal> = dogCell;
// Error: set would accept an Animal that is not a Dog
// const b: Cell<Dog> = animalCell;
// Error: get would return an Animal that is not a DogBoth assignments fail, and both failures prevent a real bug. This is the common case for mutable containers.
| Position of `T` | Variance | `Box<Dog>` to `Box<Animal>` | `Box<Animal>` to `Box<Dog>` |
|---|---|---|---|
| Return type, readonly property | Covariant | Allowed | Error |
| Function parameter | Contravariant | Error | Allowed |
| Both | Invariant | Error | Error |
| Not used at all | Bivariant | Allowed | Allowed |
Where TypeScript Is Deliberately Unsound
Two features break the rules above for convenience.
Arrays Are Covariant
Arrays both produce and consume T, so strictly they should be invariant. TypeScript treats them as covariant, because that makes everyday code such as passing a Dog[] to a function that reads Animal[] work without ceremony.
const dogs: Dog[] = [dog];
const animals: Animal[] = dogs; // allowed
animals.push({ name: "Cat" }); // compiles
dogs[1].bark(); // TypeError at runtime: bark is not a functionThe compiler accepts every line, and the program fails when it runs. If you need to guard against this, accept readonly Animal[] in functions that only read. ReadonlyArray<T> has no mutating methods, so it really is covariant.
Method Syntax Is Bivariant
With strictFunctionTypes, parameters are checked contravariantly only for function-typed properties and function type aliases. Parameters declared with method syntax are still compared bivariantly.
interface MethodCell<T> {
get(): T;
set(value: T): void;
}
let stored: Dog = dog;
const dogCell: MethodCell<Dog> = {
get() {
return stored;
},
set(value) {
stored = value;
},
};
const animalCell: MethodCell<Animal> = dogCell; // compiles, unlike Cell<T>
animalCell.set({ name: "Cat" });
stored.bark(); // TypeError at runtimeCell<T> above and MethodCell<T> have the same shape. They differ only in whether set is written as a property or as a method, and only the property version is rejected. The rule exists because many built-in interfaces, Array<T> among them, use method syntax, and strict checking would have broken a great deal of existing code.
The same applies to generic classes. A Stack<Dog> from the earlier chapter is assignable to Stack<Animal>, even though push accepts a T. Treat that as a gap in the checker, not a guarantee.
Explicit Variance Annotations
Since TypeScript 4.7 you can state the intended variance on a type parameter with in, out, or both:
interface ReadonlyBox<out T> {
get(): T;
}
interface Sink<in T> {
put: (value: T) => void;
}
interface Slot<in out T> {
get(): T;
set(value: T): void;
}The keywords mean the following:
out TmarksTas covariant. It is produced, never consumed.in TmarksTas contravariant. It is consumed, never produced.in out TmarksTas invariant.
The compiler checks each annotation against the structure of the type. This version is rejected, because T is used as an input:
// interface Bad<out T> {
// set: (value: T) => void;
// }
// Error: variance annotation does not match how T is usedThe annotations have two benefits.
- They document intent, so a later edit that adds a write method to a covariant type fails at compile time instead of silently changing the API.
- They can speed up checking for deeply recursive generic types. The compiler can skip structural comparison and use the declared variance directly.
An invariant annotation such as in out T also gives you the strict behavior for a type that uses method syntax.
Practical Guidance
- Read-only views, such as iterators, promises, and
ReadonlyArray<T>, are covariant. Use them in parameter positions when you only read. - Callbacks, comparers, event handlers, and validators are contravariant in the value they receive. A handler for a broad type can be passed where a handler for a narrow type is required.
- Mutable containers should be treated as invariant, whatever the checker allows.
- When a variance error appears, find where
Tis used in the type. A single write position is enough to make a type invariant. - If you need
Box<Dog>to be accepted asBox<Animal>, split the type. Expose a read-only interface that usesout T, and keep the mutable one separate.
Exercise
Given type Handler<T> = (event: T) => void, interface MouseEvt extends UIEvt { x: number }, and a variable h: Handler<UIEvt>, is const m: Handler<MouseEvt> = h allowed under strictFunctionTypes? Is the reverse assignment allowed? Name the variance of Handler.
Show answer
The first assignment is allowed. A handler that accepts any UIEvt can handle a MouseEvt, which is a subtype. The reverse is an error, because a handler that reads x cannot handle every UIEvt. Handler is contravariant in T, since T appears only as a parameter type.
Exercise
A class Registry<T> has items: T[], a method add(item: T): void, and a method all(): readonly T[]. Without annotations, TypeScript allows Registry<Dog> to be assigned to Registry<Animal>. Why, and how would you make the compiler reject it?
Show answer
items is a covariant array, and add uses method syntax, which is checked bivariantly, so no position forces a rejection. Adding the annotation in out T (class Registry<in out T>) declares the type invariant, and the assignment then fails. Changing add to a function-typed property, add: (item: T) => void, also makes the parameter check contravariant.