Type compatibility and variance

Advanced · 12 min

When one type can stand in for another: covariance, contravariance, why methods stay bivariant under strictFunctionTypes, and the in/out annotations.

Before thisStructural typing and excess property checksFunction type expressions and call signaturesExtending interfaces and intersection types

Andrew Burgess · 12 min

Type compatibility and variance

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Andrew BurgessReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A type `S` is assignable to `T` when every value of `S` can safely be used wherever a `T` is expected; for object types that means `S` has at least `T`'s members with compatible types.
  • Variance describes how compatibility of a wrapper follows compatibility of what it wraps: return types and read-only containers are covariant, so a `() => Dog` can stand in for a `() => Animal`.
  • Function parameters are contravariant: a function that accepts any `Animal` can stand in for one that accepts a `Dog`, but not the other way around.
  • Under `strictFunctionTypes`, parameters of function-typed properties are checked contravariantly, but parameters of methods declared with method syntax are still checked bivariantly, which is unsound but keeps types like `Array<T>` usable.
  • Mutable arrays are treated as covariant even though writing to them makes that unsound; TypeScript accepts the hole as a pragmatic trade-off.
  • Since TypeScript 4.7 a generic type parameter can be annotated `out` (covariant), `in` (contravariant) or `in out` (invariant); the compiler checks the annotation against the type's structure and uses it to speed up comparisons.

The question behind every assignment

Every time you assign a value, pass an argument, or return a result, the compiler asks one thing: can a value of this type be used safely wherever a value of that type is expected? If yes, the first type is assignable to the second.

For plain object types, structural typing answers it: the source needs at least the target’s members. The interesting cases come when types are wrapped inside other types, such as functions, arrays and generic containers. Then you need to know which direction compatibility flows. That direction is called variance.

All the examples here use this small hierarchy:

interface Animal { name: string }
interface Dog extends Animal { bark(): void }
interface Cat extends Animal { meow(): void }

const dog: Dog = { name: "Rex", bark() {} };
const animal: Animal = dog; // fine: every Dog is an Animal

Covariance: producers follow the arrow

A function that returns a Dog can stand in for one that returns an Animal. Whoever calls it expects an animal and gets a dog, which is fine.

const getDog = (): Dog => dog;
const getAnimal: () => Animal = getDog; // fine

Compatibility of the wrapper goes in the same direction as compatibility of the contents: Dog to Animal, so () => Dog to () => Animal. That’s covariance. Return types are covariant, and so are read-only containers like readonly Dog[]. Anything that only hands values out behaves this way.

Contravariance: consumers flip it

Parameters run the other way. A function that accepts any Animal can stand in for one that only needs to accept a Dog:

const describe = (a: Animal) => a.name;
const handleDog: (d: Dog) => string = describe; // fine

But not the reverse:

const barkAt = (d: Dog) => d.bark();
const handleAnimal: (a: Animal) => void = barkAt;
// Error: Type '(d: Dog) => void' is not assignable to type '(a: Animal) => void'.
//   Types of parameters 'd' and 'a' are incompatible.
//     Property 'bark' is missing in type 'Animal' but required in type 'Dog'.

handleAnimal might be called with a cat, and barkAt would crash. Compatibility of the function flips relative to its parameter: that’s contravariance. A shop that accepts all major cards can replace one that only takes Visa; a Visa-only shop can’t replace one that promises to take every card.

A type used in both positions, read and written, is invariant. Neither direction is safe.

The method exception under strictFunctionTypes

Parameter contravariance is enforced by strictFunctionTypes, part of strict. But it only covers function types written as properties. Members written with method syntax are still compared bivariantly, meaning a wider or a narrower parameter type is accepted:

interface MethodHandler { handle(a: Animal): void }
interface PropHandler { handle: (a: Animal) => void }

const m: MethodHandler = { handle: barkAt }; // allowed (bivariant)
const p: PropHandler = { handle: barkAt };
// Error: Type '(d: Dog) => void' is not assignable to type '(a: Animal) => void'.

That first assignment is unsound: m.handle(someCat) type-checks and then crashes. The exemption exists for compatibility. Built-in types such as Array<T> declare methods like push(...items: T[]). If those were checked contravariantly, Array<T> would become invariant, and huge amounts of existing code would stop compiling. If you want the strict check on your own types, write callbacks as properties.

Arrays are covariant anyway

The same pragmatism shows up with mutable arrays:

const dogs: Dog[] = [dog];
const animals: Animal[] = dogs; // allowed
animals.push({ name: "Tom", meow() {} } as Cat);
// dogs now contains a cat

Strictly, a mutable array is invariant, because it’s read and written. TypeScript treats it as covariant because the alternative is unbearable to use. You can opt into safety: assign to readonly Animal[] instead, and the write methods disappear.

in and out variance annotations

Generic types are compared by working out how each type parameter is used. Since TypeScript 4.7 you can state it instead. The generics group covers generic types in full; here you only need the annotations:

interface Producer<out T> { get: () => T }
interface Consumer<in T> { accept: (value: T) => void }
interface Cell<in out T> { get: () => T; set: (value: T) => void }

declare const dogCell: Cell<Dog>;
const animalCell: Cell<Animal> = dogCell;
// Error: Type 'Cell<Dog>' is not assignable to type 'Cell<Animal>'.

out means covariant, in means contravariant, and in out means invariant. The compiler verifies the annotation against the structure. Mark a type out T while using T as a parameter and you get an error saying the type is not assignable “as implied by variance annotation.” So annotations can’t make an unsafe type look safe.

What they do buy is clarity and speed. The intent is written at the declaration, and the compiler can compare Cell<Dog> with Cell<Animal> by checking Dog and Animal alone, without expanding every member. That matters for deeply recursive or heavily used types. For most code, inferred variance is correct and you never need them.

About the video

Andrew Burgess’s video, despite its title, is about covariance and contravariance in TypeScript. He works through when one function type can be assigned to another, looking at return types and parameter types separately and at which direction compatibility runs for each. His description notes that he once says “covariance” where he means “contravariance”, so if one statement sounds backwards, check it against the parameter rule above. The video doesn’t cover method bivariance, mutable-array covariance or the in/out annotations, which is why the text spends most of its space there.

Check yourself

  1. 01With `Dog extends Animal`, which of these compiles under `strict`, and why: assigning `(a: Animal) => string` to `(d: Dog) => string`, or assigning `(d: Dog) => void` to `(a: Animal) => void`?

    The first compiles. The target will only ever be called with dogs, and a function that handles any animal handles dogs fine. The second is rejected because the target may be called with a cat, and the dog-only function would then call `bark` on something that can't bark.

  2. 02`interface MethodHandler { handle(a: Animal): void }` accepts `{ handle: (d: Dog) => d.bark() }`, but `interface PropHandler { handle: (a: Animal) => void }` rejects it. Why?

    `strictFunctionTypes` only applies contravariant checking to function types written as property types. Members written with method syntax keep the older bivariant check, which accepts a parameter type that is either wider or narrower. The exemption exists because many built-in types, such as `Array<T>`, use method syntax and would become invariant otherwise.

  3. 03`const animals: Animal[] = dogs` compiles when `dogs` is `Dog[]`. What can go wrong, and how could you avoid it?

    Through `animals` you can push a `Cat` into what is really the `dogs` array, and later code reading `dogs` will treat that cat as a dog. TypeScript allows the assignment for convenience. Typing the target as `readonly Animal[]` removes the write methods, which makes the covariant assignment genuinely safe.

  4. 04What does `interface Cell<in out T> { get: () => T; set: (value: T) => void }` tell the compiler, and what happens if you assign `Cell<Dog>` to `Cell<Animal>`?

    It declares `T` invariant: `Cell<A>` is assignable to `Cell<B>` only when `A` and `B` are mutually assignable. Assigning `Cell<Dog>` to `Cell<Animal>` is an error, which is correct, since otherwise you could `set` a cat into a cell that other code reads as holding a dog.

  5. 05What happens if you annotate a type parameter `out T` but use `T` as a function parameter inside the type?

    The compiler checks the annotation against the structure and reports an error, saying the type is not assignable as implied by the variance annotation. Annotations can't make an unsafe type covariant; they document intent and let the compiler skip structural comparison when instantiations are compared.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark