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
DogextendsAnimal, thenDog[]is assignable toAnimal[]. - Contravariance: function parameters are contravariant in strict mode;
(animal: Animal) => voidis assignable to(dog: Dog) => voidonly 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.