Emmanuel Akinfulubi

TypeScriptClasses and OOP

Protected name and private age in TypeScript

20 An animal with a protected name and a private age

easy

Write an animal class with a protected name and a private age. Add a public method that introduces the animal using both. Only the class itself may read the age.

Stuck? Three hints, smallest first
  1. 1. The public method is the only route to the age from anywhere else.
  2. 2. A subclass may use the name but not the age. Write one and show the difference.
  3. 3. This is the same lesson as exercise 17 from the other direction, so keep it short.

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 Animal {
  constructor(
    protected name: string,
    private age: number,
  ) {}

  public introduce(): string {
    return `${this.name} is ${this.age} year(s) old`;
  }

  // Only this class can read age, so any derived value goes through here.
  public isAdult(): boolean {
    return this.age >= 2;
  }
}

class Dog extends Animal {
  constructor(name: string, age: number, private breed: string) {
    super(name, age);
  }

  // Allowed: name is protected.
  public tag(): string {
    return `${this.name} the ${this.breed}`;
  }

  // Not allowed: age is private to Animal.
  // public ageOnly(): number { return this.age; }
}

const a = new Animal('Rex', 4);
const d = new Dog('Bingo', 1, 'terrier');

console.log(a.introduce(), '| adult?', a.isAdult());
console.log(d.introduce(), '| adult?', d.isAdult());
console.log(d.tag());

test('introduce uses both fields', a.introduce(), 'Rex is 4 year(s) old');
test('derived value from the private field', a.isAdult(), true);
test('the young one is not an adult', d.isAdult(), false);
test('subclass used the protected name', d.tag(), 'Bingo the terrier');

Output


      

isAdult() is the pattern to take from this. When a field is private, everything the outside world needs from it has to be exposed as a method or getter. That is a feature: you can change how age is stored without touching a single caller.

Newsletter

New writing, when it lands.

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