Emmanuel Akinfulubi

TypeScriptClasses and OOP

Multilevel inheritance in TypeScript

12 Three levels of inheritance

fair

Write a vehicle class with a make and model, a car class extending it, and a sports car extending that. Give each its own constructor and check the fields are inherited correctly.

Stuck? Three hints, smallest first
  1. 1. Each constructor calls super() with what the level above needs.
  2. 2. Walk the prototype chain at the end to see all three links.
  3. 3. Three levels works. Ask yourself whether it reads better than two plus a property.

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 Vehicle {
  constructor(public make: string, public model: string) {}

  describe(): string {
    return `${this.make} ${this.model}`;
  }
}

class Car extends Vehicle {
  constructor(make: string, model: string, public doors: number) {
    super(make, model);
  }

  override describe(): string {
    return `${super.describe()}, ${this.doors} doors`;
  }
}

class SportsCar extends Car {
  constructor(make: string, model: string, doors: number, public topSpeed: number) {
    super(make, model, doors);
  }

  override describe(): string {
    return `${super.describe()}, top speed ${this.topSpeed}km/h`;
  }
}

const s = new SportsCar('Toyota', 'Supra', 2, 250);
console.log(s.describe());

// Every level's fields arrived.
console.log(s.make, s.model, s.doors, s.topSpeed);

// The chain, walked.
const chain: string[] = [];
let link: object | null = Object.getPrototypeOf(s);
while (link !== null && link !== Object.prototype) {
  chain.push(link.constructor.name);
  link = Object.getPrototypeOf(link);
}
console.log('chain:', chain.join(' -> '));

test('all three levels described', s.describe(), 'Toyota Supra, 2 doors, top speed 250km/h');
test('grandparent field', s.make, 'Toyota');
test('parent field', s.doors, 2);
test('own field', s.topSpeed, 250);
test('chain is three deep', chain, ['SportsCar', 'Car', 'Vehicle']);
test('it is all three types', s instanceof Car && s instanceof Vehicle, true);

Output


      

This works, and it is close to the limit of what stays readable. To know what describe() returns you now read three classes. Beyond two levels, ask whether a property such as topSpeed on Car would have done the job with less machinery.

Newsletter

New writing, when it lands.

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