Importance of Contravariance
- Flexibility: Functions can accept a wider range of inputs through contravariance. Enhances code reusability, and adaptability.
- Polymorphism: The contravariance finds the polymorphic nature in TypeScript. Functions may be polymorphic over types, permitting a number of different input types while still keeping them type-safe.
- Code Reusability: Through accepting more general kinds of types, functionalities which utilize contravariance can be used to address a variety of contexts. Doing this will help to reduce code duplication while at the same time leading to a more modular as well as maintainable codebase.
Contravariance in TypeScript
Contravariance is the contrary of covariance. In covariance, types differ in the same way as the lineage order which means a more specific type is allowed to be used for a broader type, on the other hand, contravariance reverses this trend such that a wider category can easily accept a narrower one.
Example: To demonstratee creating a food-giving system to animals that takes generalized paramters type which can handel specialized one.
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): void {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
makeSound(): void {
console.log(`${this.name} barks.`);
}
}
// Contravariant function parameter
function feedAnimal(animal: Animal): void {
console.log(`Feeding ${animal.name}`);
}
// Using contravariant function
const feedDog: (dog: Dog) => void = feedAnimal;
// Creating animal instances
const genericAnimal = new Animal("Generic Animal");
const fluffy = new Dog("Fluffy");
feedAnimal(genericAnimal);
feedDog(fluffy);
Output:
Feeding Generic Animal
Feeding Fluffy
Contact Us