Simulator
Polymorphism Playground
Swap implementations behind one Notifier contract, then step through dynamic dispatch on a list of shapes.
Runtime polymorphism
alertUser(notifier) only knows the interface. Which class runs depends on what you inject — the same idea as Nest swapping providers in tests.
polymorphism.ts
interface Notifier { notify(msg: string): string; }
function alertUser(n: Notifier) {
return n.notify("Order shipped");
}
class EmailNotifier implements Notifier {
notify(msg: string) {
return "email: " + msg;
}
}
console.log(alertUser(new EmailNotifier()));→ email: Order shipped
Dynamic dispatch
A Shape[] holds mixed types. Each area() call dispatches to the runtime class.
Circle.area()13
Square.area()?
Circle.area()?
dispatch.ts
abstract class Shape { abstract area(): number; }
class Circle extends Shape {
constructor(private r: number) { super(); }
area() { return Math.round(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), new Circle(3)];
console.log(shapes.map((s) => s.area()));