Emmanuel Akinfulubi

TypeScriptClasses and OOP

Abstract shapes with area and perimeter in TypeScript

16 Geometric shapes with area and perimeter

fair

Write an abstract geometric shape with a name and abstract methods for both area and perimeter. Implement a circle, a rectangle and a triangle.

Stuck? Three hints, smallest first
  1. 1. For the triangle, use the three sides plus Heron’s formula so area needs no height.
  2. 2. Heron: with s = (a + b + c) / 2, the area is Math.sqrt(s * (s - a) * (s - b) * (s - c)).
  3. 3. Round in the assertions, not in the methods, so the maths stays exact.

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)}`)
  );
}

abstract class GeometricShape {
  constructor(public name: string) {}

  abstract getArea(): number;
  abstract getPerimeter(): number;

  summary(): string {
    return `${this.name}: area ${this.getArea().toFixed(2)}, perimeter ${this.getPerimeter().toFixed(2)}`;
  }
}

class Circle extends GeometricShape {
  constructor(private radius: number) { super('circle'); }
  override getArea(): number { return Math.PI * this.radius ** 2; }
  override getPerimeter(): number { return 2 * Math.PI * this.radius; }
}

class Rectangle extends GeometricShape {
  constructor(private width: number, private height: number) { super('rectangle'); }
  override getArea(): number { return this.width * this.height; }
  override getPerimeter(): number { return 2 * (this.width + this.height); }
}

class Triangle extends GeometricShape {
  constructor(private a: number, private b: number, private c: number) {
    super('triangle');
    const valid = a + b > c && b + c > a && a + c > b;
    if (!valid) throw new RangeError(`no triangle has sides ${a}, ${b}, ${c}`);
  }
  override getPerimeter(): number { return this.a + this.b + this.c; }
  override getArea(): number {
    // Heron's formula, so no height is needed.
    const s = this.getPerimeter() / 2;
    return Math.sqrt(s * (s - this.a) * (s - this.b) * (s - this.c));
  }
}

const shapes: GeometricShape[] = [new Circle(2), new Rectangle(3, 4), new Triangle(3, 4, 5)];
for (const s of shapes) console.log(s.summary());

let refused = '';
try { new Triangle(1, 2, 10); } catch (err) { refused = (err as RangeError).message; }
console.log('refused:', refused);

test('circle area', Number(shapes[0]?.getArea().toFixed(2)), 12.57);
test('rectangle area', shapes[1]?.getArea(), 12);
test('right triangle area via Heron', shapes[2]?.getArea(), 6);
test('triangle perimeter', shapes[2]?.getPerimeter(), 12);
test('an impossible triangle is refused', refused.includes('no triangle'), true);

Output


      

Two things beyond the inheritance. Heron’s formula gets the area from the three sides alone, which is why the constructor does not need a height. And the constructor validates the triangle inequality, so an impossible shape cannot exist in the first place rather than silently returning NaN.

Newsletter

New writing, when it lands.

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