Skip to the content.

Chapter 8: Variance - When Is Box<Cat> a Box<Animal>?

Runnable examples: examples/ch08-variance.ts

If Cat is a subtype of Animal, is a list of cats a list of animals? Is a function that takes a cat a function that takes an animal? The answer depends on how the type parameter is used, and that property is called variance.

Covariance: outputs

type Producer<T> = () => T;
// Producer<Cat> is assignable to Producer<Animal>

Anyone expecting an animal from a producer is happy to receive a cat. The subtyping direction is preserved: covariant.

Contravariance: inputs

type Consumer<T> = (value: T) => void;
// Consumer<Animal> is assignable to Consumer<Cat>, NOT the other way

A function that can handle any animal can certainly handle a cat. But a function that only handles cats (it calls meow()) cannot be given an arbitrary animal. The direction is reversed: contravariant. TypeScript enforces this for function types under strictFunctionTypes, which is part of strict.

Invariance: inputs and outputs

type Ref<T> = { get: () => T; set: (value: T) => void };
// Neither Ref<Cat> -> Ref<Animal> nor Ref<Animal> -> Ref<Cat> is allowed

Reading wants covariance, writing wants contravariance; both together leave only exact matches.

Quick reference

How T is used Variance F<Cat> to F<Animal>? F<Animal> to F<Cat>?
Only returned or read Covariant Yes No
Only accepted as a parameter Contravariant No Yes
Both read and written Invariant No No
Not used Bivariant (irrelevant) Yes Yes

The holes: where TypeScript is deliberately unsound

Method parameters are bivariant

interface MethodStyle<T> { handle(value: T): void }       // method syntax
interface PropertyStyle<T> { handle: (value: T) => void } // property syntax

strictFunctionTypes applies only to function types written with property or arrow syntax. Parameters of methods are still checked bivariantly, so MethodStyle<Cat> is assignable to MethodStyle<Animal>. The examples show this compiling, then crashing at runtime when a plain animal is passed to a cat-only handler.

Why keep the hole? Many built-in types (like DOM and array methods) rely on it, and making methods strictly contravariant would break huge amounts of existing code.

Practical advice: in your own interfaces, when a callback type matters, declare it with property syntax (handle: (value: T) => void) to get the strict check.

Mutable arrays are covariant

const cats: Cat[] = [tom];
const animals: Animal[] = cats; // allowed
animals.push({ name: "Rex" });  // compiles, and now `cats` contains a non-cat

A mutable array is really invariant (you can read and write), but TypeScript treats it as covariant for convenience. Defend yourself by accepting readonly T[] (or ReadonlyArray<T>) in functions that only read; readonly arrays are safely covariant.

Variance annotations: in and out

Since TypeScript 4.7 you can state variance on type parameters:

interface Source<out T> { read(): T }       // covariant
interface Sink<in T> { write(value: T): void } // contravariant
// `in out T` means invariant

TypeScript checks the annotation against the structure of the type. Annotations document intent, can speed up checking of complex types, and catch accidental changes in how a type parameter is used. One caveat follows from the method hole above: with interface Source<out T> { write: (v: T) => void } (property syntax) TypeScript reports an error, but the same input written as a method, write(v: T): void, is accepted because method parameters are bivariant.

Check yourself

  1. Is (a: Animal) => Cat assignable to (c: Cat) => Animal?
  2. Why does accepting readonly Animal[] avoid the array covariance problem?
  3. You want callers to be unable to pass a narrower handler to your subscribe API. Should the handler be declared as a method or as a property?
Answers 1. Yes: parameters are contravariant (`Animal` accepts every `Cat`) and returns are covariant (`Cat` is an `Animal`). 2. A readonly array cannot be pushed to, so nothing wrong can be written through it. 3. As a property with a function type, so it is checked contravariantly.

Next: Chapter 9, Type-Level Programming