Polymorphism is a core concept in object-oriented programming that allows objects of different classes to be treated as objects of a common superclass. In TypeScript, polymorphism enables developers to write more flexible and reusable code. It allows methods to be defined in a base class and overridden in derived classes, providing a way to perform the same operation in different ways depending on the object that is invoking the method.
In TypeScript, polymorphism can be achieved through method overriding and interfaces. By using these features, developers can create a system where different classes can be interacted with through a common interface or base class.
Method overriding occurs when a derived class provides a specific implementation of a method that is already defined in its base class. This allows the derived class to customize or extend the behavior of the base class method.
class Animal {
makeSound(): void {
console.log("Some generic animal sound");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Bark");
}
}
class Cat extends Animal {
makeSound(): void {
console.log("Meow");
}
}
function animalSound(animal: Animal) {
animal.makeSound();
}
const dog = new Dog();
const cat = new Cat();
animalSound(dog); // Output: Bark
animalSound(cat); // Output: Meow
Another way to achieve polymorphism in TypeScript is through interfaces. By defining a common interface that multiple classes implement, you can ensure that these classes provide specific methods or properties, allowing them to be used interchangeably.
interface Shape {
area(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
area(): number {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
area(): number {
return this.width * this.height;
}
}
function printArea(shape: Shape) {
console.log(`Area: ${shape.area()}`);
}
const circle = new Circle(5);
const rectangle = new Rectangle(4, 6);
printArea(circle); // Output: Area: 78.53981633974483
printArea(rectangle); // Output: Area: 24
In summary, polymorphism in TypeScript classes is a powerful feature that enhances code flexibility and reusability. By leveraging method overriding and interfaces, developers can create systems that are easier to maintain and extend.