Covariance and contravariance help control how types relate when you use them in functions or collections. They make sure your program stays safe when you replace one type with another.
Covariance and contravariance in Typescript
interface Producer<T> {
produce: () => T;
}
interface Consumer<T> {
consume: (item: T) => void;
}TypeScript uses structural typing and does not have explicit in or out keywords like some languages, but it supports covariance and contravariance in function types.
Return types are usually covariant (you can return a subtype), and parameter types are contravariant (you can accept a supertype).
type Animal = { name: string };
type Dog = { name: string; bark: () => void };
// Covariance example:
let getAnimal: () => Animal;
let getDog: () => Dog = () => ({ name: 'Rex', bark: () => console.log('Woof') });
getAnimal = getDog; // Allowed: Dog is subtype of Animaltype Animal = { name: string };
type Dog = { name: string; bark: () => void };
// Contravariance example:
let feedDog: (dog: Dog) => void;
let feedAnimal: (animal: Animal) => void = (animal) => console.log(animal.name);
feedDog = feedAnimal; // Allowed: feedAnimal accepts any Animal, so it can feed a Doglet animals: Animal[] = [{ name: 'Cat' }]; let dogs: Dog[] = [{ name: 'Rex', bark: () => console.log('Woof') }]; // Arrays are covariant in TypeScript animals = dogs; // Allowed but can be unsafe if you add a Cat to animals later
This program shows covariance by assigning a function returning Dog to a variable expecting a function returning Animal. It also shows contravariance by assigning a function accepting Animal to a variable expecting a function accepting Dog.
type Animal = { name: string };
type Dog = { name: string; bark: () => void };
function getAnimal(): Animal {
return { name: 'Generic Animal' };
}
function getDog(): Dog {
return { name: 'Rex', bark: () => console.log('Woof') };
}
let animalProducer: () => Animal;
let dogProducer: () => Dog = getDog;
// Covariance: dogProducer can be assigned to animalProducer
animalProducer = dogProducer;
console.log(animalProducer().name); // Prints 'Rex'
function feedAnimal(animal: Animal) {
console.log(`Feeding ${animal.name}`);
}
let dogFeeder: (dog: Dog) => void;
// Contravariance: feedAnimal can be assigned to dogFeeder
dogFeeder = feedAnimal;
dogFeeder({ name: 'Buddy', bark: () => console.log('Woof') });Covariance means you can use a more specific type where a general type is expected, usually in return types.
Contravariance means you can use a more general type where a specific type is expected, usually in function parameters.
TypeScript checks these rules mostly in function types to keep your code safe.
Covariance lets you replace a type with a more specific one safely, mainly in outputs.
Contravariance lets you replace a type with a more general one safely, mainly in inputs.
Understanding these helps you write flexible and safe TypeScript code with functions and collections.
Practice
covariance in TypeScript?Solution
Step 1: Understand covariance meaning
Covariance means you can use a more specific type where a general type is expected, usually for outputs like return values.Step 2: Compare with contravariance
Contravariance is about inputs and generalizing types, so it is different from covariance.Final Answer:
It allows replacing a type with a more specific type safely, mainly in outputs. -> Option AQuick Check:
Covariance = more specific output type [OK]
- Confusing covariance with contravariance
- Thinking covariance applies to inputs
- Believing covariance restricts type changes
Solution
Step 1: Understand contravariance in parameters
Contravariance means a function can accept a more general type as input than expected.Step 2: Compare parameter types
Given Dog extends Animal, accepting Animal (more general) instead of Dog is contravariant.Final Answer:
(input: Animal) => void -> Option BQuick Check:
Contravariance = input type generalizes [OK]
- Choosing more specific input types for contravariance
- Mixing input and output type variance
- Ignoring inheritance relationships
class Animal { name: string = 'animal'; }
class Dog extends Animal { breed: string = 'bulldog'; }
let func1: (dog: Dog) => Dog = (d) => d;
let func2: (animal: Animal) => Animal = func1;
const result = func2(new Animal());
console.log(result.name);What will be the output when this code runs?
Solution
Step 1: Analyze function type assignment
func1 expects a Dog parameter and returns Dog. Assigning func1 to func2 which expects Animal parameter and returns Animal is invalid because parameter types are contravariant and return types covariant.Step 2: Understand TypeScript type checking
TypeScript disallows assigning a function expecting a more specific parameter (Dog) to one expecting a more general parameter (Animal) due to contravariance rules.Final Answer:
Type error at assignment -> Option DQuick Check:
Contravariance blocks incompatible parameter types [OK]
- Assuming assignment is allowed without error
- Ignoring contravariance in function parameters
- Expecting runtime output instead of compile error
interface Producer<out T> {
produce: () => T;
}
interface Consumer<in T> {
consume: (item: T) => void;
}
let producer: Producer<Animal> = { produce: () => new Animal() };
let consumer: Consumer<Dog> = { consume: (d) => console.log(d.breed) };
consumer = producer; // Error hereSolution
Step 1: Identify variance roles
Producer is covariant (outputs), Consumer is contravariant (inputs). Assigning producer to consumer mixes these roles incorrectly.Step 2: Understand type incompatibility
Producer<Animal> cannot be assigned to Consumer<Dog> because their variance directions conflict, causing a type error.Final Answer:
Assigning Producer<Animal> to Consumer<Dog> is invalid due to variance mismatch. -> Option CQuick Check:
Variance mismatch causes assignment error [OK]
- Ignoring variance annotations (in/out)
- Assuming unrelated interfaces can be assigned
- Confusing input and output roles
Animal as input and returns a more specific subtype of Animal. Which function type signature correctly uses covariance and contravariance to allow this flexibility?Solution
Step 1: Identify input contravariance
The callback input should be a general type (Animal) to accept any subtype safely (contravariance).Step 2: Identify output covariance
The callback returns a more specific subtype (Dog), allowing covariance in the return type.Step 3: Match function signature
function processAnimal(callback: (input: Animal) => Dog): Dogmatches these rules: input is Animal (general), output is Dog (specific), and the function returns Dog.Final Answer:
function processAnimal(callback: (input: Animal) => Dog): Dog -> Option AQuick Check:
Input general, output specific = contravariant input, covariant output [OK]
- Reversing input and output types
- Using more specific input types causing errors
- Ignoring return type covariance
Ready to prove it?
Pass the test and this pattern moves unknown
