Polymorphism in TypeScript - A Simplified Explanation


Introduction

Polymorphism is a key concept in Object-Oriented Programming (OOP) that allows objects of different classes to be treated as objects of a common superclass. In TypeScript, polymorphism simplifies working with objects by enabling code that can work with objects of multiple types in a uniform way. In this guide, we'll explore the concept of polymorphism and its implementation in TypeScript.


Understanding Polymorphism

Polymorphism is the ability of different objects to respond to the same method or property in a way that is appropriate for their respective types. This allows you to write code that works with a variety of objects without needing to know their specific types. It promotes flexibility and code reusability.


Defining a Common Interface

To achieve polymorphism in TypeScript, you often define a common interface or superclass with shared methods. Subclasses then implement these methods in their own way.


Example:

interface Shape {
calculateArea(): number;
}
class Circle implements Shape {
constructor(private radius: number) {}
calculateArea() {
return Math.PI * this.radius ** 2;
}
}
class Rectangle implements Shape {
constructor(private width: number, private height: number) {}
calculateArea() {
return this.width * this.height;
}
}

Utilizing Polymorphism

Once you have objects that implement a common interface or extend a common superclass, you can use them interchangeably.


Example:

function printArea(shape: Shape) {
console.log("Area: " + shape.calculateArea());
}
const myCircle = new Circle(5);
const myRectangle = new Rectangle(3, 4);
printArea(myCircle); // Area: 78.53981633974483
printArea(myRectangle); // Area: 12

Benefits of Polymorphism

Polymorphism promotes code flexibility and reusability. It allows you to write code that can work with various objects as long as they adhere to a common interface or superclass. This simplifies code maintenance and extends the lifespan of your software.


Conclusion

Polymorphism is a fundamental concept in TypeScript and OOP that simplifies code and promotes flexibility. By defining common interfaces or superclasses and allowing different objects to implement them in their own way, you can create more adaptable and maintainable code that can work with a variety of objects without the need for type-specific logic.