Advanced · 10 of 12 · 15 min read
Variance
Which way a type parameter is allowed to move — covariance, contravariance, bivariance and invariance, where TypeScript is deliberately unsound, and how to read the resulting errors.
- Variance
- Structural typing
Variance is the rule that decides, given that Dog is assignable to Animal, whether
Container<Dog> is assignable to Container<Animal>. The answer depends entirely on where the
parameter sits inside the container.
The four
class Animal { name = ""; }
class Dog extends Animal { bark() {} }
// Covariant: output only.
interface Producer<T> { get(): T }
declare const dogProducer: Producer<Dog>;
const animalProducer: Producer<Animal> = dogProducer; // ok
// Contravariant: input only.
interface Consumer<T> { set: (value: T) => void }
declare const animalConsumer: Consumer<Animal>;
const dogConsumer: Consumer<Dog> = animalConsumer; // ok
console.log(animalProducer.get().name, typeof dogConsumer.set);
Both directions are safe, and each for the same reason once you say it out loud. Anything that
hands out Dogs can stand in for something that hands out Animals, because every Dog is an
Animal. Anything that accepts any Animal can stand in for something that accepts Dogs,
because every Dog it is given is an acceptable Animal.
class Animal { name = ""; }
class Dog extends Animal { bark() {} }
// Invariant: both positions.
interface Box<T> { get(): T; set: (value: T) => void }
declare const dogBox: Box<Dog>;
// const animalBox: Box<Animal> = dogBox; // rejected
// const narrower: Box<Dog> = {} as Box<Animal>; // also rejected
console.log(dogBox.get().name);
Neither direction is safe for a Box: reading from it wants covariance, writing to it wants
contravariance, so only an exact match is allowed.
Position of T |
Variance | Container<Dog> → Container<Animal> |
|---|---|---|
| Return type only | covariant | allowed |
| Parameter only (property syntax) | contravariant | rejected; the reverse is allowed |
| Both | invariant | rejected both ways |
| Method shorthand parameter | bivariant | allowed both ways — unsound |
| Array element | covariant | allowed — unsound |
readonly array element |
covariant | allowed, and sound |
| Not used at all | bivariant | allowed both ways |
Function assignability, in one rule
class Animal { name = ""; }
class Dog extends Animal { bark() {} }
type DogHandler = (dog: Dog) => Animal;
const wider: (animal: Animal) => Dog = (animal) => new Dog();
const a: DogHandler = wider; // parameter wider, return narrower — allowed
const narrower: (dog: Dog) => Animal = (dog) => dog;
// const b: (animal: Animal) => Dog = narrower; // rejected on both counts
console.log(a(new Dog()).name);
Accept more, return less. A function is assignable when it demands no more of its caller and promises no less to them. That one sentence covers method overrides, callback parameters, and every interface a class implements.
The two unsoundnesses
TypeScript knowingly allows two things that can fail at runtime, both because the sound rule broke too much existing code.
Arrays are covariant:
class Animal {}
class Dog extends Animal { bark() {} }
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs; // allowed — same array
animals.push(new Animal()); // and now `dogs` has an Animal in it
// dogs[1]!.bark(); // compiles, throws at runtime
console.log(dogs.length); // 2
An array is a Box: it reads and it writes, so it should be invariant. Treating it as covariant is
what lets numbers.concat, items.forEach and every T[] parameter accept a subtype array
without ceremony — and the cost is the hole above.
The sound version exists and is one keyword:
class Animal {}
class Dog extends Animal { bark() {} }
function count(items: readonly Animal[]) { return items.length; }
const dogs: Dog[] = [new Dog()];
console.log(count(dogs)); // accepted, and `count` cannot push
readonly T[] has no push, so T only appears in output position and covariance is justified.
Use it on every parameter that only reads — it accepts more inputs and is safer, which is a rare
combination.
Method shorthand is bivariant:
interface WithMethod { handle(value: string | number): void }
interface WithProperty { handle: (value: string | number) => void }
const narrow = (value: string) => console.log(value.length);
const a: WithMethod = { handle: narrow }; // allowed — bivariant
// const b: WithProperty = { handle: narrow }; // rejected under strictFunctionTypes
a.handle("ok");
// a.handle(42); // compiles, and `narrow` would call .length on a number
The two declarations describe the same runtime shape and are checked differently. strictFunctionTypes
turned on contravariant checking for function types but deliberately left methods bivariant,
because Array<T>’s own methods — and most of the standard library — depend on it.
The practical rule: declare a callback with property syntax when you want it checked, and
accept that a method() on an interface is checked loosely.
Variance in your own generics
The compiler measures variance structurally, so a parameter’s variance is a consequence of the code rather than a declaration:
interface Repo<T> {
all(): readonly T[]; // output
save(item: T): void; // input — makes it invariant
}
interface ReadRepo<T> {
all(): readonly T[]; // covariant
}
class Animal { name = ""; }
class Dog extends Animal {}
declare const dogRepo: Repo<Dog>;
// const animalRepo: Repo<Animal> = dogRepo; // rejected — invariant
const animalReader: ReadRepo<Animal> = dogRepo; // allowed — covariant
console.log(animalReader.all().length);
Splitting the read half out of an interface is how a container becomes assignable in the direction
callers want. That is the same move as readonly T[], and the same move as Iterable<T> being
covariant while Array<T> is not.
in and out make the measured variance explicit:
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 }
// interface Broken<out T> { set: (value: T) => void }
// Type 'T' is declared covariant but occurs in a contravariant position.
declare const producer: Producer<string>;
const wider: Producer<unknown> = producer;
console.log(typeof wider.get);
They change nothing about what is allowed — the compiler already knew. What they buy is an error at the declaration when someone adds a method that breaks the intended variance, instead of a confusing error at a use site in another package. Worth it on a widely-used interface; noise anywhere else.
Reading a variance error
Type 'Repo<Dog>' is not assignable to type 'Repo<Animal>'.
Types of property 'save' are incompatible.
Type '(item: Dog) => void' is not assignable to type '(item: Animal) => void'.
Types of parameters 'item' and 'item' are incompatible.
Type 'Animal' is not assignable to type 'Dog'.
The last line looks backwards, and that is the signature of a variance error: the comparison
flipped because the mismatch is in a parameter position. Read it as “to use this where a
Repo<Animal> is expected, save would have to accept any Animal — and it only accepts
Dog”. Whenever the innermost line names the two types in the opposite order from the first line,
you are looking at contravariance rather than a mistake.
Where this actually comes up
Three everyday cases that are variance questions in disguise:
class Animal { name = ""; }
class Dog extends Animal { bark() {} }
// 1. A handler map — contravariance makes the generic handler reusable.
type Handler<T> = (event: T) => void;
const logAny: Handler<Animal> = (event) => console.log(event.name);
const dogHandlers: Handler<Dog>[] = [logAny, (dog) => dog.bark()];
// 2. Promise is covariant — so is awaiting one.
declare const dogPromise: Promise<Dog>;
const animalPromise: Promise<Animal> = dogPromise;
// 3. A read-only parameter accepts more.
function names(items: readonly Animal[]) { return items.map((i) => i.name); }
console.log(dogHandlers.length, typeof animalPromise.then, names([new Dog()]));
The first is why one generic logger can go in a list of specific handlers. The second is why
Promise<T> composes without friction. The third is the single highest-value habit from this
whole lecture.
Common mistakes
T[] on a parameter that only reads
Mistake. function total(items: Item[]).
Why it fails. It is less permissive and less safe: it rejects a readonly Item[] the caller
has, and it permits the function to mutate the caller’s array.
What to do instead. readonly Item[], which accepts both and forbids mutation.
Expecting strictFunctionTypes to catch a method
Mistake. Assuming the flag makes all parameter checking contravariant.
Why it fails. Method shorthand stays bivariant by design, so handle(value: string | number)
accepts a (value: string) => void.
What to do instead. Declare checked callbacks as properties: handle: (value: X) => void.
Fighting an invariance error with as
Mistake. const animalRepo = dogRepo as Repo<Animal>.
Why it fails. The invariance was correct — something can now save(new Cat()) into a
dog repository.
What to do instead. Split the interface, so the read half is covariant and assignable on its
own.
Check yourself
3 questions from the bank on what you just read. Answering here does not affect your quiz history.
Array assignability in TypeScript is deliberately unsound, and this is the demonstration.
Why does this compile despite being obviously wrong?
class Animal {}
class Dog extends Animal { bark() {} }
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs;
animals.push(new Animal());Under strictFunctionTypes, how are function parameters checked?
Optional properties make two unrelated shapes accidentally compatible.
Why is this assignment allowed?
interface Options { timeout?: number }
const options: Options = { retries: 3 } as { retries: number };Further reading
Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.
Reaching the end of a lecture marks it as read.