Start learning free

LESSON 65 OF 70 · PROJECTS: OBJECT-ORIENTED

Bank Account in TypeScript: Encapsulation with Private # Fields

Practice Read the full explanation

Build a BankAccount class that keeps its balance private and lets other code change it only through methods that check the rules. This is encapsulation: the object protects its own data.

Private balance. Declare the balance as a truly private field with the # prefix, #balance: number. Code outside the class cannot read or write it, and inside you reach it as this.#balance.

What the class must have (TypeScript):

  • constructor(initialBalance: number): creates an account that starts with the given balance.
  • deposit(amount: number): void: adds amount to the balance. If amount is zero or negative, do nothing (no error, the balance stays the same).
  • withdraw(amount: number): boolean: if amount is zero or negative, or larger than the balance, change nothing and return false. Otherwise subtract it from the balance and return true. Withdrawing exactly the whole balance is allowed (the balance becomes 0).
  • getBalance(): number: returns the current balance. It is the only way for outside code to read it.

The driver. The driver at the end of the starter code is already written and uses your class. It runs these checks:

const account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
account.withdraw(200);
console.log("Balance: " + account.getBalance());
account.deposit(-20);
account.deposit(0);
account.withdraw(-5);
console.log("Balance: " + account.getBalance());
if (account.withdraw(120)) {
    console.log("Withdrew all");
}
console.log("Balance: " + account.getBalance());
if (!account.withdraw(1)) {
    console.log("Rejected");
}

Walk through it: start with 100, deposit 50 (150), withdraw 30 (120), withdraw 200 is refused (still 120). Then deposit -20, deposit 0 and withdraw -5 are all ignored (still 120). Withdrawing 120 succeeds and empties the account, so the balance is 0, and withdrawing 1 more is refused.

Expected output:

Balance: 120
Balance: 120
Withdrew all
Balance: 0
Rejected

Both deposit and withdraw start with a guard that rejects amount <= 0. Write the guard first, then the change to the balance.

Declare #balance: number; in the class body, then in the constructor write this.#balance = initialBalance;.

if (amount <= 0 || amount > this.#balance) return false;, then this.#balance -= amount; and return true;.

class BankAccount {
    #balance: number;

    constructor(initialBalance: number) {
        this.#balance = initialBalance;
    }

    deposit(amount: number): void {
        if (amount <= 0) return;
        this.#balance += amount;
    }

    withdraw(amount: number): boolean {
        if (amount <= 0 || amount > this.#balance) return false;
        this.#balance -= amount;
        return true;
    }

    getBalance(): number {
        return this.#balance;
    }
}

const account = new BankAccount(100);
account.deposit(50);
account.withdraw(30);
account.withdraw(200);
console.log("Balance: " + account.getBalance());
account.deposit(-20);
account.deposit(0);
account.withdraw(-5);
console.log("Balance: " + account.getBalance());
if (account.withdraw(120)) {
    console.log("Withdrew all");
}
console.log("Balance: " + account.getBalance());
if (!account.withdraw(1)) {
    console.log("Rejected");
}

STEP 1 OF 13
    Ctrl + Enter to check

    TYPESCRIPT · PROJECTS: OBJECT-ORIENTED

    Bank Account in TypeScript, explained

    Problem overview

    The lesson asks for a BankAccount class that keeps its balance private. Other code can't touch the number directly. It can only call methods, and those methods enforce the rules of the account. This is encapsulation: an object owns its data and decides how that data may change.

    The class has four members:

    • constructor(initialBalance: number) starts the account with the given balance.
    • deposit(amount: number): void adds to the balance, but ignores an amount that is zero or negative.
    • withdraw(amount: number): boolean subtracts from the balance and returns true, unless the amount is zero or negative or larger than the balance. Then it changes nothing and returns false. Withdrawing exactly the whole balance is allowed.
    • getBalance(): number is the only way to read the balance from outside.

    The driver starts an account with 100, deposits 50, withdraws 30 and then tries to withdraw 200. It prints the balance, tries three invalid operations, withdraws the remaining 120, and tries to withdraw 1 more. The expected output is Balance: 120, Balance: 120, Withdrew all, Balance: 0 and Rejected.

    Approach: a private field and methods that guard it

    The balance lives in a field named #balance. The # prefix makes it a JavaScript private field: only code written inside the class body can use it, as this.#balance. Every change to the balance goes through deposit or withdraw, so the rules are written once and can't be bypassed.

    Both methods follow the same pattern: guard first, change second. A guard is an if at the top of the method that leaves immediately when the request is invalid. Past the guard the code can assume the amount is acceptable and update the balance without further checks. deposit leaves silently, because it returns void. withdraw returns false to tell the caller the money didn't move, and true at the end when it did.

    Tracing the driver

    Running the lesson's calls one at a time, with the balance after each:

    CallReturnsBalance after
    deposit(50)nothing150
    withdraw(30)true120
    withdraw(200)false120
    deposit(-20)nothing120
    deposit(0)nothing120
    withdraw(-5)false120
    withdraw(120)true0
    withdraw(1)false0

    Step by step

    1. Declare the class BankAccount and write its closing brace at once. Everything below goes inside it.
    2. Declare the private field #balance: number;. The declaration is required: a # field must be declared in the class body before this.#balance can be used.
    3. Start the constructor with one parameter, initialBalance: number.
    4. Store the starting balance in this.#balance, so a new account begins with the amount it is given.
    5. Start deposit, with a number parameter named amount and the return type void.
    6. Add the deposit guard: a one-line if that returns when amount is zero or less.
    7. Add the amount to this.#balance. Only positive amounts get past the guard.
    8. Start withdraw, taking amount and returning a boolean.
    9. Add the withdrawal guard with two conditions joined by ||: the amount isn't positive, or it is more than the balance. In either case return false. The comparison is >, not >=, so asking for exactly the whole balance is allowed.
    10. Subtract the amount from this.#balance.
    11. Return true, because reaching this line means the money left the account.
    12. Start getBalance, with no parameters and the return type number.
    13. Return this.#balance. The caller gets a copy of the number, so reading it can't change the account.

    The solution in TypeScript

    class BankAccount {
        #balance: number;
    
        constructor(initialBalance: number) {
            this.#balance = initialBalance;
        }
    
        deposit(amount: number): void {
            if (amount <= 0) return;
            this.#balance += amount;
        }
    
        withdraw(amount: number): boolean {
            if (amount <= 0 || amount > this.#balance) return false;
            this.#balance -= amount;
            return true;
        }
    
        getBalance(): number {
            return this.#balance;
        }
    }
    
    const account = new BankAccount(100);
    account.deposit(50);
    account.withdraw(30);
    account.withdraw(200);
    console.log("Balance: " + account.getBalance());
    account.deposit(-20);
    account.deposit(0);
    account.withdraw(-5);
    console.log("Balance: " + account.getBalance());
    if (account.withdraw(120)) {
        console.log("Withdrew all");
    }
    console.log("Balance: " + account.getBalance());
    if (!account.withdraw(1)) {
        console.log("Rejected");
    }
    

    TypeScript details worth knowing

    • #balance against private balance. TypeScript also has a private keyword, but it is checked only by the compiler and erased from the JavaScript. A # field is private at run time too. Outside the class, account.#balance is a compile error (Property '#balance' is not accessible outside class 'BankAccount' because it has a private identifier), and in the compiled JavaScript it is a syntax error, so the program doesn't even start. With private x in a class, reading p.x from outside also gets a compiler error, yet the compiled program runs and prints the value.
    • Private fields are hidden from enumeration. For an account created with 100, Object.keys(account) is [] and JSON.stringify(account) is {}. Looking for account.balance gives undefined, because no property of that name exists.
    • The one-line if. if (amount <= 0) return; is an if without braces. In deposit, a bare return is valid because the return type is void. In withdraw, the guard returns a value.
    • Short-circuit ||. In amount <= 0 || amount > this.#balance, the second comparison runs only when the first is false.
    • Types are not run-time checks. The number annotation stops the compiler from accepting a string, but nothing is checked once the code is compiled. If a caller bypasses the types with a cast, deposit("5" as any) on an account holding 100 makes the balance 1005, because += then joins strings.

    Complexity

    Every method does a fixed number of comparisons and at most one addition or subtraction, so each call takes O(1) time. An account stores one number, so the space is O(1).

    Edge cases and common mistakes

    • Using >= in the withdrawal guard. This refuses the withdrawal of exactly the balance. The driver's withdraw(120) on a balance of 120 must succeed and leave 0.
    • Forgetting the amount <= 0 check in withdraw. withdraw(-5) would then pass the second condition and increase the balance by 5.
    • Zero. A deposit or withdrawal of 0 is rejected with <= 0. Writing < 0 would let the zero amounts through. The balance wouldn't change, but withdraw(0) would return true.
    • Changing the balance before the guard. If withdraw subtracted first and checked afterwards, a refused request would still have changed the balance.
    • NaN. Every comparison with NaN is false, so neither guard rejects it. After deposit(NaN) on an account holding 100, getBalance() returns NaN. The lesson's tests don't use it, but a real account would add a check such as Number.isFinite(amount).
    • Decimal amounts. number is a double, so a balance built from 0.1 and a deposit of 0.2 reads 0.30000000000000004. Money is often stored in whole cents to avoid this.
    • Forgetting this.. Inside a method, #balance on its own is not a variable. It must be written this.#balance.

    Testing

    • A new account with 100: getBalance() returns 100.
    • After deposit(50), then withdraw(30): withdraw returned true and the balance is 120.
    • withdraw(200) on a balance of 120 returns false and the balance stays 120.
    • deposit(-20), deposit(0) and withdraw(-5) all leave the balance at 120.
    • withdraw(120) returns true and the balance becomes 0, after which withdraw(1) returns false.
    Keep going with TypeScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free