Emmanuel Akinfulubi

TypeScriptClasses and OOP

Abstract employee salary calculation in TypeScript

15 Abstract employees with different pay rules

fair

Write an abstract employee class with a name, an id and an abstract salary calculation. Write a full-time and a part-time employee whose pay is worked out differently.

Stuck? Three hints, smallest first
  1. 1. Full-time pay might be an annual figure; part-time is usually a rate times hours.
  2. 2. Keep the pay numbers whole to avoid floating-point noise in the assertions.
  3. 3. A payroll total over a mixed array is the clearest proof the polymorphism works.

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)}`)
  );
}

abstract class Employee {
  constructor(
    public name: string,
    public employeeId: string,
  ) {}

  abstract calculateSalary(): number;

  payslip(): string {
    return `${this.employeeId} ${this.name}: ₦${this.calculateSalary().toLocaleString('en-NG')}`;
  }
}

class FullTimeEmployee extends Employee {
  constructor(name: string, id: string, private annualSalary: number) {
    super(name, id);
  }
  // Monthly pay from an annual figure.
  override calculateSalary(): number {
    return Math.round(this.annualSalary / 12);
  }
}

class PartTimeEmployee extends Employee {
  constructor(name: string, id: string, private hourlyRate: number, private hours: number) {
    super(name, id);
  }
  override calculateSalary(): number {
    return this.hourlyRate * this.hours;
  }
}

const staff: Employee[] = [
  new FullTimeEmployee('Amaka Obi', 'EMP-001', 4_800_000),
  new PartTimeEmployee('Chidi Eze', 'EMP-002', 2_500, 80),
];

for (const s of staff) console.log(s.payslip());

const payroll = staff.reduce((n, s) => n + s.calculateSalary(), 0);
console.log('monthly payroll:', payroll);

test('full-time monthly', staff[0]?.calculateSalary(), 400000);
test('part-time monthly', staff[1]?.calculateSalary(), 200000);
test('payroll total', payroll, 600000);
test('payslip formats the name and id', staff[1]?.payslip().startsWith('EMP-002 Chidi Eze'), true);

Output


      

The payroll line never asks who is full-time. Adding a contractor with a completely different formula means one new class and no change to the total. Note the numeric separators, 4_800_000, which are just for readability and vanish at runtime.

Newsletter

New writing, when it lands.

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