Sub topic 15
Variance in Generic Types
Assume you know basic TypeScript types, unions, functions, interfaces, type aliases, and generic syntax. This chapter focuses on how a generic type changes when its type argument changes.
Variance describes whether a relationship between types is preserved by a generic type.
Suppose Dog extends Animal. A generic type can behave in several ways:
| Variance | Relationship | Example |
|---|---|---|
| Covariant | `Container<Dog>` can be used as `Container<Animal>` | A producer that only returns values |
| Contravariant | `Handler<Animal>` can be used as `Handler<Dog>` | A consumer that accepts values |
| Invariant | Neither direction is safe | A mutable container that reads and writes values |
Covariance: producing values
A producer returns values of type T. A producer of dogs can safely be used where a producer of animals is expected because every dog is an animal.
interface Animal {
name: string;
}
interface Dog extends Animal {
bark(): void;
}
interface Producer<T> {
get(): T;
}
const dogs: Producer<Dog> = {
get: () => ({ name: "Rex", bark: () => console.log("woof") })
};
const animals: Producer<Animal> = dogs;
console.log(animals.get().name);The code using animals only expects an Animal, so it does not need to call bark.
ReadonlyArray<Dog> can similarly be used as ReadonlyArray<Animal>. Reading a dog as an animal is safe because the array cannot be changed through that reference.
Contravariance: consuming values
A consumer accepts values of type T. The direction reverses. A handler that accepts any Animal can safely handle a Dog, but a handler that accepts only dogs cannot safely handle every animal.
With strictFunctionTypes enabled, function parameters are checked contravariantly.
type Handler<T> = (value: T) => void;
const animalHandler: Handler<Animal> = animal => {
console.log(animal.name);
};
const dogHandler: Handler<Dog> = dog => {
dog.bark();
};
const safeHandler: Handler<Dog> = animalHandler;
// const unsafeHandler: Handler<Animal> = dogHandler; // ErrorThe safe assignment works because animalHandler can process every dog. The reverse assignment could give dogHandler an animal that is not a dog.
Invariance and mutable generics
A mutable container both produces and consumes T.
interface Box<T> {
value: T;
}Treating Box<Dog> as Box<Animal> would allow someone to place a non-dog animal into a box that was created for dogs. Treating it in the opposite direction could allow code to read a value that is not a dog. For mutable structures, neither assignment direction is generally safe.
Use separate read-only and write-only views when possible. This exposes the variance you actually need and prevents accidental mutation.
TypeScript-specific gotchas
TypeScript often infers variance from how a type parameter is used. It also uses structural typing, so the shape of a type matters more than its declared name.
Function syntax matters. Under strictFunctionTypes, function properties receive stricter parameter checks than many method declarations. Methods retain some historical bivariance for compatibility, which can permit assignments that are less safe than expected.
Prefer strict: true, use readonly for producers, and test assignments that cross type boundaries. Variance is most useful as a design question: does this API only return values, only accept values, or do both?
Exercise
If Dog extends Animal, which assignment is safe: Producer<Dog> to Producer<Animal>, or Producer<Animal> to Producer<Dog>?
Show answer
Producer<Dog> to Producer<Animal> is safe because every Dog is an Animal, and the consumer only reads the produced value.