Implementing Covariance in TypeScript
In TypeScript, covariance primarily applies to function return types and arrays, let’s see how covariance can be implemented:
Syntax:
// Covariant function return type
function getAnimal(): Animal {
return new Dog();
}
// Using covariant function
const animal: Animal = getAnimal();
Covariance in TypeScript
Covariance in Typescript shows the connection between different types in that the compatibility’s direction is parallel to that of inheritance. In a nutshell, it means that a more specialized kind is able to work with a more general type. It also applies to arrays and return types of functions, for instance, a function which returns a more specific kind can be utilized in the context where only broader kinds are expected and vice versa when an array sub-type is replaced by its parent supertype.
Contact Us