Skip to content
AgileLogics
4 min read

Access Modifiers

Prerequisites: Classes with types

public (the default), private, and protected control which code can access a class member.

class BankAccount {
    private balance: number;

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

    deposit(amount: number) {
        this.balance += amount;
    }

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

const account = new BankAccount(100);
account.balance; // Property 'balance' is private and only accessible within class 'BankAccount'

private is enforced only at compile time (it's erased from the compiled JavaScript) — for a genuinely runtime-enforced private field, use JavaScript's native #balance syntax instead.