Emmanuel Akinfulubi

TypeScriptClasses and OOP

private vs protected in TypeScript

17 private and protected on a student

fair

Write a student class with a private name and a protected id. Add a public method that prints both. Show that a subclass can reach the protected field but nothing outside can reach either.

Stuck? Three hints, smallest first
  1. 1. private means this class only. protected means this class and its subclasses.
  2. 2. Both are compile-time only. Neither survives into the JavaScript output.
  3. 3. Write a subclass that reads the protected field to prove the difference.

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

  public displayInfo(): string {
    return `${this.name} (#${this.studentId})`;
  }
}

class Undergraduate extends Student {
  constructor(name: string, id: number, private year: number) {
    super(name, id);
  }

  // Allowed: studentId is protected, and this is a subclass.
  idCard(): string {
    return `year ${this.year}, id ${this.studentId}`;
  }

  // Not allowed, because name is private to Student:
  // nameOnly(): string { return this.name; }
}

const s = new Student('Amaka Obi', 17);
const u = new Undergraduate('Chidi Eze', 42, 2);

console.log(s.displayInfo());
console.log(u.displayInfo());
console.log(u.idCard());

// From outside, both are refused at compile time:
// s.name;        // Property 'name' is private
// s.studentId;   // Property 'studentId' is protected

// But they are only compile-time. The data is right there at runtime:
const leaked = Object.keys(s);
console.log('own keys at runtime:', leaked);

test('public method sees both', s.displayInfo(), 'Amaka Obi (#17)');
test('subclass reached the protected field', u.idCard(), 'year 2, id 42');
test('inherited method still works', u.displayInfo(), 'Chidi Eze (#42)');
test('neither modifier hides the data at runtime', leaked, ['name', 'studentId']);

Output


      

The last assertion is the honest part. private and protected are checked by the compiler and then erased, so Object.keys and JSON.stringify still show everything. If you need real privacy that survives to runtime, use a # field, which the next exercise does.

Newsletter

New writing, when it lands.

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