Method overriding in TypeScript
11 Overriding a draw method
easyWrite a shape class with a colour and a draw() method that says a shape is being drawn. Then write a circle class that overrides draw() with something specific to circles.
Stuck? Three hints, smallest first
- 1. The child’s method wins because lookup stops at the first match it finds.
- 2. Mark the override with the
overridekeyword so a rename upstream cannot silently orphan it. - 3. Put both in an array typed as the parent and loop; each answers in its own way. That is polymorphism.
const same = (a: unknown, b: unknown): boolean =>
JSON.stringify(a) === JSON.stringify(b);
function test(name: string, got: unknown, want: unknown): void {
console.log(
(same(got, want) ? 'ok ' : 'FAIL ') + name +
(same(got, want) ? '' : ` got ${JSON.stringify(got)}, want ${JSON.stringify(want)}`)
);
}
class Shape {
constructor(public colour: string) {}
draw(): string {
return `drawing a ${this.colour} shape`;
}
}
class Circle extends Shape {
constructor(colour: string, public radius: number) {
super(colour);
}
override draw(): string {
return `drawing a ${this.colour} circle, radius ${this.radius}`;
}
}
class Square extends Shape {
constructor(colour: string, public side: number) {
super(colour);
}
override draw(): string {
return `drawing a ${this.colour} square, side ${this.side}`;
}
}
// One loop, three types, no type names mentioned inside it.
const shapes: Shape[] = [
new Shape('grey'),
new Circle('red', 3),
new Square('blue', 4),
];
const drawn = shapes.map((s) => s.draw());
for (const line of drawn) console.log(line);
test('the base version', drawn[0], 'drawing a grey shape');
test('the circle override', drawn[1], 'drawing a red circle, radius 3');
test('the square override', drawn[2], 'drawing a blue square, side 4');
test('three shapes drawn', drawn.length, 3);
Output
The loop is the payoff. It is typed Shape[] and never asks what it is holding, yet each object answers correctly. Adding a triangle means writing one class and changing nothing here.