Contravariance on TypeScript Function Parameters

Do you know about TypeScript contravariance on function parameters. It means function types are contravariant. It means for function types, parameter types go the “opposite way” compared to the usual “subtype” story.

Let us say you have two classed Animal and Dog.

class Animal {
readonly legs = 4;
}
class Dog extends Animal {
bark() {
console.log('Woof!');
}
}

And two types created as shown below,

type AcceptDog = (d: Dog) => void;
type AcceptAnimal = (a: Animal) => void;

Now you have two functions,

const handleAnimal: AcceptAnimal = (a) => {
console.log(a.legs);
};
const handleDog: AcceptDog = (d) => {
d.bark();
};

Now let us use these functions and types. Below is very much allowed and you can pass the type derived from Animal to Dog.


const f :AcceptAnimal = handleAnimal; // correct 
const g :AcceptDog = handleDog; // correct
const i :AcceptDog = handleAnimal; // correct

But if you pass Dog to Animal, TypeScript complains about that.

const j :AcceptAnimal = handleDog; // error

For above assignment, TypeScript gives compile time error,

Dog is a subtype of Animal that means , every dog is an animal  So normally, If something works with Animal, it automatically works with Dog. But in context of function types, it reverses and parameter types go the “opposite way” compared to the usual “subtype” story.

  • If Dog is a subtype of Animal (a dog is an animal),
  • then a function that accepts Animal is more useful than one that only accepts Dog.
  • So (animal: Animal) => void can be used where (dog: Dog) => void is expected — but not the other way around.

That “parameters flip the direction” is contravariance in TypeScript function parameters.

I hope now you know about contravariance in TypeScript. Thanks for reading.

Also, we are hosting the 8th edition of India’s Largest Angular Conference in Gurgaon on 11 April. You can find more details here – https://www.ng-ind.com/home


Discover more from Dhananjay Kumar

Subscribe to get the latest posts sent to your email.

Published by Dhananjay Kumar

Dhananjay Kumar is founder of NomadCoder and ng-India

Leave a comment

Discover more from Dhananjay Kumar

Subscribe now to keep reading and get access to the full archive.

Continue reading