Bank account class with a protected balance in TypeScript
18 A bank account with a protected balance
fairWrite a bank account with a private account number and a protected balance starting at zero. Add public deposit and withdraw methods. Only the class and its subclasses may touch the balance.
Stuck? Three hints, smallest first
- 1. Refuse a withdrawal that would overdraw, and refuse a deposit that is not positive.
- 2. Return
thisfrom both so calls can chain. - 3. A savings subclass that adds interest is the natural way to prove
protectedworks.
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 BankAccount {
protected balance = 0;
constructor(private accountNumber: string) {}
public deposit(amount: number): this {
if (!Number.isFinite(amount) || amount <= 0) {
throw new RangeError(`deposit must be positive, got ${amount}`);
}
this.balance += amount;
return this;
}
public withdraw(amount: number): this {
if (amount > this.balance) {
throw new RangeError(`cannot withdraw ${amount}; balance is ${this.balance}`);
}
this.balance -= amount;
return this;
}
public statement(): string {
return `${this.accountNumber}: ₦${this.balance}`;
}
}
class SavingsAccount extends BankAccount {
constructor(accountNumber: string, private rate: number) {
super(accountNumber);
}
// Allowed, because balance is protected.
addInterest(): this {
this.balance += Math.round(this.balance * this.rate);
return this;
}
}
const current = new BankAccount('0123456789');
current.deposit(50_000).withdraw(20_000);
console.log(current.statement());
const savings = new SavingsAccount('9876543210', 0.1);
savings.deposit(100_000).addInterest();
console.log(savings.statement());
const refusals: string[] = [];
for (const attempt of [() => current.withdraw(999_999), () => current.deposit(-5)]) {
try { attempt(); } catch (err) { refusals.push((err as RangeError).message); }
}
test('deposit then withdraw', current.statement(), '0123456789: ₦30000');
test('interest was added by the subclass', savings.statement(), '9876543210: ₦110000');
test('overdraw refused', refusals[0]?.includes('cannot withdraw'), true);
test('negative deposit refused', refusals[1]?.includes('must be positive'), true);
test('chaining worked', current.deposit(1).withdraw(1).statement(), '0123456789: ₦30000');
Output
Returning this is what makes deposit(50_000).withdraw(20_000) read as one sentence. The return type is written this rather than BankAccount on purpose: that way savings.deposit(...) still gives you a SavingsAccount, so you can carry on and call addInterest().