~/alexsh.blog

$ cat advanced-typescript/09-variance-and-contravariance.md

Variance and Contravariance

February 9, 20261 min readpart 09/20

Difficulty: Advanced. Prerequisites: Generics, type compatibility, function types, inheritance.

Variance describes how subtyping relationships between complex types relate to subtyping between their components. Understanding covariance, contravariance, and invariance is essential for designing type-safe generic APIs and understanding why union-to-intersection conversion works.

Key concepts

  • Covariance: subtype relationship preserved (output positions like return types)
  • Contravariance: subtype relationship reversed (input positions like parameters)
  • Invariance: no subtype relationship (both in and out positions)
  • Using 'in' and 'out' modifiers for explicit variance annotation (TS 4.7+)
  • Why function parameters are contravariant and return types are covariant

Example

codets
interface Producer<out T> { produce(): T; }  // Covariant
interface Consumer<in T> { consume(x: T): void; }  // Contravariant
interface Box<T> { get(): T; set(x: T): void; }  // Invariant

class Animal { name = ''; }
class Dog extends Animal { bark() {} }

// Covariant - preserved
const dogs: Dog[] = [new Dog()];
const animals: readonly Animal[] = dogs; // OK

// Contravariant - reversed
type Handler<T> = (x: T) => void;
const animalH: Handler<Animal> = (a) => console.log(a.name);
const dogH: Handler<Dog> = animalH; // OK - contravariant!

// This is why union-to-intersection works:
// Contravariant position collects into intersection
// (A => void) | (B => void) in param position becomes A & B

// Real-world: Effect-TS annotates variance on core types for safety + perf
interface Predicate<in A> { (a: A): boolean }
interface Refinement<in A, out B extends A> { (a: A): a is B }
// Effect<out A, out E = never, out R = never> — all covariant

Resources

Practice

Hints

  • Think of covariance as "output" (return types) and contravariance as "input" (parameters).
  • Use the "in" and "out" modifiers (TS 4.7+) to explicitly annotate variance on your generic types.