Emmanuel Akinfulubi

TypeScriptClasses and OOP

Extend a class (inheritance) in TypeScript

3 A subclass that adds a capability

easy

Given a car class, write an SUV class that extends it and adds a flag for whether it can go off-road. Include a method that toggles the flag and reports the new state.

Stuck? Three hints, smallest first
  1. 1. class SUV extends Car, and the subclass constructor must call super(...) first.
  2. 2. Call super() before you touch this, or you get a ReferenceError.
  3. 3. Returning this from the toggle would let calls chain; returning a message is what the exercise asks for.

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

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

class SUV extends Car {
  offRoad: boolean;

  constructor(make: string, model: string, offRoad = false) {
    super(make, model);      // must run before any use of `this`
    this.offRoad = offRoad;
  }

  toggleOffRoad(): string {
    this.offRoad = !this.offRoad;
    return this.offRoad
      ? `${this.describe()}: off-road mode on`
      : `${this.describe()}: back to road mode`;
  }
}

const suv = new SUV('Toyota', 'Prado');

console.log(suv.describe());
const first = suv.toggleOffRoad();
const second = suv.toggleOffRoad();
console.log(first);
console.log(second);

test('inherited describe works', suv.describe(), 'Toyota Prado');
test('starts on the road', new SUV('Kia', 'Sportage').offRoad, false);
test('first toggle turns it on', first, 'Toyota Prado: off-road mode on');
test('second toggle turns it off', second, 'Toyota Prado: back to road mode');
test('an SUV is also a Car', suv instanceof Car, true);

Output


      

describe() was never written in SUV, and it works, because lookup walks up to Car.prototype. The default value on offRoad = false means callers can leave it out, which is usually kinder than making every argument required.

Newsletter

New writing, when it lands.

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