Variance
In one line
Variance determines if T→U means G<T>→G<U> (covariant), G<U>→G<T> (contravariant), or neither (invariant).
In simple words
Variance describes how subtyping of generic types relates to their type parameters:
- Covariant — if
Dog extends Animal, thenArray<Dog> extends Array<Animal>. The container preserves the subtyping direction. Arrays, Promises, and readonly properties are covariant.
- Contravariant — if
Dog extends Animal, then(x: Animal) => void extends (x: Dog) => void. Function parameters reverse the direction. A function accepting any Animal can be used where a function accepting Dogs is expected.
- Invariant — neither direction works. Mutable properties are invariant because they're both read (covariant) and written (contravariant).
TypeScript checks function parameters contravariantly (with strictFunctionTypes). Understanding variance prevents type unsoundness.
Example
class Animal { name = "animal"; }
class Dog extends Animal { bark() {} }
// Covariant: Dog[] is assignable to Animal[]
const dogs: Dog[] = [new Dog()];
const animals: Animal[] = dogs; // OK — covariant
// Contravariant: (x: Animal) => void is assignable to (x: Dog) => void
const handleAnimal = (a: Animal) => console.log(a.name);
const handleDog: (d: Dog) => void = handleAnimal; // OK — contravariant
// Invariant: mutable property
type Box<T> = { value: T }; // T is invariant (read + write)
// const dogBox: Box<Dog> = { value: new Dog() };
// const animalBox: Box<Animal> = dogBox; // Error! invariantArrays are covariant, function params are contravariant, mutable properties are invariant. Variance determines assignability of generic types.
Common confusions
Confused with: generic constraint
The difference: A generic constraint (T extends Animal) restricts what T can be. Variance describes how G<T> relates to G<U> when T relates to U. Constraints are about valid type arguments; variance is about assignability of instantiated generic types.
Related terms
Related Resources
Related Lessons
- TypeScript Advanced Types
Variance.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.