Polymorphism is a fundamental concept in object-oriented programming that allows objects of different types to be treated as objects of a common base type. In TypeScript, polymorphism enables developers to write more flexible and reusable code.
At its core, polymorphism means "many forms." It allows a single interface to represent different underlying forms (data types or classes). TypeScript supports two main types of polymorphism:
Subtype polymorphism is achieved through inheritance and interfaces. It allows a derived class to be treated as its base class.
interface Animal {
makeSound(): void;
}
class Dog implements Animal {
makeSound() {
console.log("Woof!");
}
}
class Cat implements Animal {
makeSound() {
console.log("Meow!");
}
}
function animalSound(animal: Animal) {
animal.makeSound();
}
const dog = new Dog();
const cat = new Cat();
animalSound(dog); // Output: Woof!
animalSound(cat); // Output: Meow!
In this example, both Dog
and Cat
classes implement the Animal
interface. The animalSound
function can accept any object that implements the Animal
interface, demonstrating polymorphism.
Parametric polymorphism is implemented using generics in TypeScript. It allows writing code that can work with multiple types.
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>(100);
The identity
function is polymorphic as it can work with any type. The type T
is determined when the function is called.
Polymorphism is a powerful feature in TypeScript that enhances code flexibility and reusability. By understanding and applying both subtype and parametric polymorphism, developers can create more robust and maintainable TypeScript applications.
For more advanced topics related to polymorphism, explore generics in TypeScript and abstract classes.