0
0
Typescriptprogramming~5 mins

Polymorphism through interfaces in Typescript

Choose your learning style9 modes available
Introduction

Polymorphism lets us use different objects in the same way. Interfaces help us define a common shape for these objects.

When you want different objects to share the same behavior but have different details.
When you want to write code that works with many types without changing it.
When you want to make your code easier to extend with new types later.
When you want to ensure certain methods exist on different objects.
When you want to treat different objects uniformly in a collection.
Syntax
Typescript
interface InterfaceName {
  methodName(): ReturnType;
}

class ClassName implements InterfaceName {
  methodName(): ReturnType {
    // implementation
  }
}

Interfaces define what methods or properties a class must have.

Classes use implements to promise they follow the interface.

Examples
Two classes implement the same interface but have different speak sounds.
Typescript
interface Speaker {
  speak(): void;
}

class Dog implements Speaker {
  speak() {
    console.log("Woof!");
  }
}

class Cat implements Speaker {
  speak() {
    console.log("Meow!");
  }
}
Function accepts any object that implements Speaker and calls speak method.
Typescript
function makeSpeak(speaker: Speaker) {
  speaker.speak();
}

const dog = new Dog();
const cat = new Cat();

makeSpeak(dog); // Woof!
makeSpeak(cat); // Meow!
Sample Program

This program shows two classes, Car and Boat, both implementing Vehicle interface. The travel function calls move on any Vehicle.

Typescript
interface Vehicle {
  move(): void;
}

class Car implements Vehicle {
  move() {
    console.log("The car drives on the road.");
  }
}

class Boat implements Vehicle {
  move() {
    console.log("The boat sails on the water.");
  }
}

function travel(vehicle: Vehicle) {
  vehicle.move();
}

const myCar = new Car();
const myBoat = new Boat();

travel(myCar);
travel(myBoat);
OutputSuccess
Important Notes

Interfaces only describe the shape; they do not create code themselves.

Polymorphism helps keep code flexible and easy to change.

Always name interfaces clearly to show what behavior they expect.

Summary

Polymorphism lets different objects be used the same way.

Interfaces define the common methods objects must have.

Classes implement interfaces to promise they have those methods.