Polymorphism
One interface, many implementations — runtime and compile-time forms.
18 minLevel 10 of 20
One contract, many forms
Polymorphism lets you write code against a base type or interface while runtime objects vary. Nest controllers depend on service abstractions; tests inject fakes — same idea.
Try the Polymorphism Playground for dynamic dispatch.
Runtime polymorphism
interface Notifier { notify(msg: string): void; }
class EmailNotifier implements Notifier {
notify(msg: string) { console.log("email:", msg); }
}
class SmsNotifier implements Notifier {
notify(msg: string) { console.log("sms:", msg); }
}
function alertUser(n: Notifier) { n.notify("shipped"); }
alertUser(new EmailNotifier());
alertUser(new SmsNotifier());Dynamic dispatch
Which method runs depends on the runtime type. A list of Shape may contain circles and rectangles — each area() resolves differently.
Dispatch
abstract class Shape { abstract area(): number; }
class Circle extends Shape {
constructor(private r: number) { super(); }
area() { return Math.PI * this.r * this.r; }
}
class Square extends Shape {
constructor(private s: number) { super(); }
area() { return this.s * this.s; }
}
const shapes: Shape[] = [new Circle(2), new Square(3)];
console.log(shapes.map((s) => Math.round(s.area())));Compile-time polymorphism
Overloads and generics provide compile-time flexibility. TypeScript function overloads document multiple call shapes with one implementation.
Overloads
function id(x: string): string;
function id(x: number): number;
function id(x: string | number) { return x; }
console.log(id("a"), id(1));Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice