Make balance readable but not writable from outside the class.
Code outside BankAccount can set balance to anything. Change the class so callers can still read account.balance, but only deposit and withdraw can change it, both at compile time and at runtime.
class BankAccount { balance = 0; deposit(amount: number): void { this.balance += amount; } withdraw(amount: number): void { if (amount > this.balance) throw new RangeError("Insufficient funds"); this.balance -= amount; }} // const account = new BankAccount();// account.deposit(50);// account.balance; // 50// account.balance = 1e6; // should be a type errorThe answer
Write it yourself first. Then compare it with a reference solution and the checks it passes.
Checking your sign-in…