Emmanuel Akinfulubi

TypeScriptClasses and OOP

Validate constructor arguments in TypeScript

8 A constructor that refuses a bad age

fair

Write a student class with a name and an age. The constructor must check the age: if it is not a positive number, fall back to zero rather than storing nonsense.

Stuck? Three hints, smallest first
  1. 1. The type number permits -5, 0, 2.5 and NaN. Only a runtime check rules those out.
  2. 2. Number.isFinite(age) && age > 0 covers the realistic cases.
  3. 3. Consider whether falling back silently is right, or whether throwing would serve the caller better. Say which you chose and why.

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 {
  readonly name: string;
  readonly age: number;

  constructor(name: string, age: number) {
    this.name = name;
    // A positive, finite number, or fall back to 0 as the exercise asks.
    this.age = Number.isFinite(age) && age > 0 ? age : 0;
  }

  describe(): string {
    return this.age === 0
      ? `${this.name}, age not on record`
      : `${this.name}, age ${this.age}`;
  }
}

// The stricter alternative, for comparison.
class StrictStudent {
  constructor(public readonly name: string, public readonly age: number) {
    if (!Number.isFinite(age) || age <= 0) {
      throw new RangeError(`${name}: age must be a positive number, got ${age}`);
    }
  }
}

const good = new Student('Amaka Obi', 14);
const negative = new Student('Chidi Eze', -3);
const notANumber = new Student('Bola Ade', NaN);

console.log(good.describe());
console.log(negative.describe());
console.log(notANumber.describe());

let refused = '';
try { new StrictStudent('Bad', -1); } catch (err) { refused = (err as RangeError).message; }
console.log('strict version says:', refused);

test('a good age is kept', good.age, 14);
test('a negative age becomes 0', negative.age, 0);
test('NaN becomes 0', notANumber.age, 0);
test('the message reflects it', negative.describe(), 'Chidi Eze, age not on record');
test('the strict version refuses instead', refused.includes('positive number'), true);

Output


      

Both versions are shown because the choice matters more than the code. Falling back to 0 means bad data enters the system quietly and someone debugs it next month. Throwing means the caller finds out immediately. The exercise asked for the fallback; in real code I would usually throw.

Newsletter

New writing, when it lands.

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