Emmanuel Akinfulubi

TypeScriptClasses and OOP

Protected properties in a subclass in TypeScript

19 A car with protected make and model

easy

Write a car class whose make and model are protected. Add a public method returning them as one string. Show a subclass using them and an outside caller being refused.

Stuck? Three hints, smallest first
  1. 1. Parameter properties accept modifiers: constructor(protected make: string).
  2. 2. The subclass can read the fields; code outside the family cannot.
  3. 3. Returning a formatted string from a public method is how the outside world gets the data.

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

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

class ElectricCar extends Car {
  constructor(make: string, model: string, private rangeKm: number) {
    super(make, model);
  }

  // Allowed: both fields are protected, and this is a subclass.
  public getFullInfo(): string {
    return `${this.make} ${this.model}, ${this.rangeKm}km range`;
  }
}

const c = new Car('Toyota', 'Corolla');
const e = new ElectricCar('BYD', 'Dolphin', 420);

console.log(c.getCarInfo());
console.log(e.getCarInfo());
console.log(e.getFullInfo());

// From outside the family, both are refused:
// c.make;    // Property 'make' is protected and only accessible within class 'Car' and its subclasses.

test('public accessor works', c.getCarInfo(), 'Toyota Corolla');
test('inherited accessor works', e.getCarInfo(), 'BYD Dolphin');
test('subclass read both protected fields', e.getFullInfo(), 'BYD Dolphin, 420km range');
test('an ElectricCar is a Car', e instanceof Car, true);

Output


      

Compare this with exercise 17. There the id was protected and the name private, so the subclass could reach one and not the other. Here both are protected, which is the right default when you expect the class to be extended.

Newsletter

New writing, when it lands.

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