Introduction
Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common superclass. It enables code reuse, improves modularity, and promotes flexibility in your applications.
What is Polymorphism?
Polymorphism can be defined as the ability of an object to take on many forms. In the context of TypeScript, it means that a variable or function can accept inputs of different types.
Upcasting and Downcasting
In TypeScript, polymorphism is achieved through inheritance. Upcasting refers to treating a derived class object as an instance of its base class. Downcasting, on the other hand, is the process of treating a base class object as an instance of its derived class.
class Animal {
eat() {
console.log('The animal is eating.');
}
}
class Dog extends Animal {
eat() {
console.log('The dog is eating.');
}
}
const animal: Animal = new Dog(); // Upcasting
animal.eat(); // Output: The dog is eating.
const dog: Dog = animal as Dog; // Downcasting