Emmanuel Akinfulubi

TypeScriptClasses and OOP

Constructor overloading in TypeScript

6 Two ways to build a student

fair

Write a student class that can be created either with a name and a roll number, or with a name alone when the roll number is not yet known. Show both.

Stuck? Three hints, smallest first
  1. 1. TypeScript allows overload signatures on a constructor, but only one implementation body.
  2. 2. An optional parameter, rollNumber?: number, is simpler and usually enough.
  3. 3. With exactOptionalPropertyTypes on, an optional property will not accept an explicit undefined; use number | null if "unknown" is a real state.

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 {
  name: string;
  rollNumber: number | null;

  // Two ways in, described for the caller...
  constructor(name: string, rollNumber: number);
  constructor(name: string);
  // ...and one body that handles both.
  constructor(name: string, rollNumber?: number) {
    this.name = name;
    this.rollNumber = rollNumber ?? null;
  }

  describe(): string {
    return this.rollNumber === null
      ? `${this.name}, roll number not yet assigned`
      : `${this.name}, roll number ${this.rollNumber}`;
  }

  get hasRoll(): boolean {
    return this.rollNumber !== null;
  }
}

const known = new Student('Amaka Obi', 17);
const unknown = new Student('Chidi Eze');

console.log(known.describe());
console.log(unknown.describe());

// A third call shape is refused, because no overload matches:
// const bad = new Student(17);

test('with a roll number', known.describe(), 'Amaka Obi, roll number 17');
test('without one', unknown.describe(), 'Chidi Eze, roll number not yet assigned');
test('the flag reflects it', known.hasRoll, true);
test('and the other way', unknown.hasRoll, false);
test('missing becomes null, not undefined', unknown.rollNumber, null);

Output


      

I used number | null rather than an optional property on purpose. "Not yet assigned" is a real state worth naming, and with exactOptionalPropertyTypes switched on an optional field cannot be set to undefined explicitly, so null avoids a fight. The two overload signatures document the call shapes; the single body does the work.

Newsletter

New writing, when it lands.

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