Skip to content

Lesson 7 of 9 · 26m

Variance: Why Types That Look Compatible Sometimes Are Not

Covariance, contravariance, invariance, and TypeScript's pragmatic unsoundness — explained through the bugs variance prevents and the ones it permits.

Variance is the type system's answer to substitution: if every cat is an animal, can I use a list of cats as a list of animals? Sometimes. Can I use a function that accepts animals where one that accepts cats is expected? Also sometimes — but in the opposite direction. If those sentences feel slippery, that is exactly why variance matters.

Substitution has direction

interface Animal { name: string }
interface Cat extends Animal { purrs: boolean }

const cats: Cat[] = [{ name: "Miso", purrs: true }];
const animals: Animal[] = cats; // compiles — covariant array reads

Reading a Cat where an Animal is expected is safe because every cat has at least the animal shape. But mutation exposes the problem:

animals.push({ name: "Bear" }); // accepted through Animal[]
cats[0].purrs;                  // uh oh — runtime data may not be a Cat

TypeScript knowingly allows some of this unsoundness for ergonomics. In strict application code, prefer readonly Animal[] when you only need reads. Removing mutation makes covariance honest.

Function parameters flip direction

A function that can handle any Animal can safely serve where a handler for Cat is expected. A function that only handles Cat cannot serve where an Animal handler is required:

type Handler<T> = (value: T) => void;

const handleAnimal: Handler<Animal> = (animal) => console.log(animal.name);
const handleCat: Handler<Cat> = (cat) => console.log(cat.purrs);

const usable: Handler<Cat> = handleAnimal; // safe
// const wrong: Handler<Animal> = handleCat; // unsafe under strictFunctionTypes

Inputs are contravariant; outputs are covariant. You do not need to memorize the words if you remember the rule: consumers can accept broader inputs and produce narrower outputs.

Mutable containers are invariant in spirit

A Box<Cat> cannot be a Box<Animal> if it has both read and write operations. Writes require the exact type; reads allow substitution. That is why APIs that only consume data are easier to type soundly than APIs that consume and mutate it.

Field notes

  • strictFunctionTypes should stay on. Turning it off hides real callback bugs, especially around event handlers.
  • Method parameters in interfaces are historically bivariant in TypeScript; function-property syntax is stricter.
  • If a generic API feels impossible to assign, ask whether the type parameter is used in an input, an output, or both.
  • Use readonly input types at public API boundaries. They increase compatibility without weakening the implementation.

Was this lesson helpful?

Sign in to rate