Emmanuel Akinfulubi

TypeScriptClasses and OOP

Shape and Circle class inheritance in TypeScript

7 A shape and a circle that extends it

easy

Write a shape class holding a colour. Then write a circle class that extends it, taking a colour and a radius and passing the colour up to the parent.

Stuck? Three hints, smallest first
  1. 1. The subclass constructor takes both values and hands one of them to super().
  2. 2. The parent field is available on the child through this once super() has run.
  3. 3. A getter for the area reads better than a method, since it takes no arguments.

The answer, and proof it works

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) {}

  describe(): string {
    return `a ${this.colour} shape`;
  }
}

class Circle extends Shape {
  constructor(colour: string, public radius: number) {
    super(colour);      // the colour goes up to Shape
  }

  get area(): number {
    return Math.PI * this.radius ** 2;
  }

  // Extending rather than replacing: reuse the parent's sentence.
  override describe(): string {
    return `${super.describe()}, a circle of radius ${this.radius}`;
  }
}

const c = new Circle('red', 3);

console.log(c.describe());
console.log('colour from the parent:', c.colour);
console.log('area:', c.area.toFixed(2));

test('parent field was set through super', c.colour, 'red');
test('own field was set', c.radius, 3);
test('area', Number(c.area.toFixed(2)), 28.27);
test('describe extends the parent', c.describe(), 'a red shape, a circle of radius 3');
test('a Circle is a Shape', c instanceof Shape, true);

Output


      

Note super.describe() inside the override. The child does not repeat the parent’s wording; it calls it and adds to it. When the parent’s sentence changes, the child follows for free.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.