What is type variance in TypeScript

· Category: TypeScript

Short answer

Type variance describes how subtyping relationships between complex types relate to their components. TypeScript uses structural typing with specific variance rules for functions, arrays, and generic parameters.

How it works

  • Covariance: if Dog extends Animal, then Dog[] is assignable to Animal[].
  • Contravariance: function parameters are contravariant in strict mode; (animal: Animal) => void is assignable to (dog: Dog) => void only if the parameter is a supertype.
  • Bivariance: method parameters are bivariant by default for compatibility.
  • Invariance: a type is invariant if it is neither covariant nor contravariant, such as with MutableArray<T>.

Why it matters

Understanding variance prevents subtle type safety holes, especially when designing generic containers and event handlers. Strict function types (strictFunctionTypes) enforce safer contravariance for function parameters.