Emmanuel Akinfulubi

TypeScriptClasses and OOP

Static math helper class in TypeScript

22 A static maths helper

easy

Write a class with static methods for add, subtract, multiply and divide. Each takes two numbers and returns the result. Handle division by zero.

Stuck? Three hints, smallest first
  1. 1. None of these needs an instance, so every method is static.
  2. 2. 1 / 0 is Infinity in JavaScript, not an error. Decide whether to allow that.
  3. 3. A class of only static methods is really a namespace. A plain object of functions would do the same job.

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 MathOps {
  static add(a: number, b: number): number { return a + b; }
  static subtract(a: number, b: number): number { return a - b; }
  static multiply(a: number, b: number): number { return a * b; }

  static divide(a: number, b: number): number {
    // JavaScript would hand back Infinity rather than complaining.
    if (b === 0) throw new RangeError('cannot divide by zero');
    return a / b;
  }
}

console.log(MathOps.add(2, 3));
console.log(MathOps.subtract(10, 4));
console.log(MathOps.multiply(6, 7));
console.log(MathOps.divide(20, 4));

let refused = '';
try { MathOps.divide(1, 0); } catch (err) { refused = (err as RangeError).message; }
console.log('divide by zero:', refused);

// What JavaScript does if you do not guard it:
const unguarded = 1 / 0;
console.log('unguarded 1 / 0 is', unguarded);

test('add', MathOps.add(2, 3), 5);
test('subtract', MathOps.subtract(10, 4), 6);
test('multiply', MathOps.multiply(6, 7), 42);
test('divide', MathOps.divide(20, 4), 5);
test('divide by zero refused', refused, 'cannot divide by zero');
test('and this is why', unguarded, Infinity);

Output


      

The last assertion is the reason for the guard. 1 / 0 is Infinity, a perfectly valid number, so nothing in the type system will ever catch it; it just spreads through your arithmetic until something looks wrong three screens later.

Newsletter

New writing, when it lands.

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