I want to share a small part of wikipedia description firstly then will continue with example codes.
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-23.38.40-1024x176.png)
Assume that we work with below types.
Animal is Supertype.
Dog and Cat are Subtype.
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-23.11.41-1024x813.png)
Covariance
Covariance means that Subtypes can be assigned to Supertypes. This is also known as Polymorphism or Subtyping. So Covariance = Polymorphism = Subtyping
In other words, Dog(Subtype) can be assigned to Animal(Subtype) or Dog(Subtype)
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-19.48.20-1024x506.png)
Generic types are also covariant.
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-19.54.06-1024x485.png)
Contravariance
Function's parameters are covariant so it mean that when we need to assign a function to a variable, right side of assignment should be Supertype and right side of assignment should be Subtype.
Notice that variable type of a5 in below screenshot is a function which accepts Dog(Subtype of Animal) parameter and returns Animal(Supertype) but when assigning a function which accepts Animal(Supertype) parameter and returns Animal. Strange part is here instead of Subtyping, function's parameter accepts Supertype.
When we call getAnimalInfo with a Supertype Dog, the implementation of getAnimalInfo function accepts Supertype Animal so it can reach only Animal fields and functions(behaviours) not Subtype behaviours like bark() function in Dog.
const getAnimalInfo: (p: Dog) => string = (p: Animal) => {
return p.name;
};
getAnimalInfo(new Dog("Markus"));
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-21.13.32-1024x643.png)
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-21.24.39-1024x492.png)
![](https://kenanhancer.com/wp-content/uploads/2022/04/Screenshot-2022-04-03-at-22.58.33-1024x734.png)