← Back to all tutorials

Public, Private & Readonly

Access modifiers in TypeScript classes — controlling property visibility and mutability.

Public, Private & Readonly

TypeScript adds access modifiers to control how class properties can be accessed.

Access Modifiers

ModifierAccessModify
public✅ Anywhere✅ Anywhere
private❌ Only inside class❌ Only inside class
readonly✅ Anywhere❌ Cannot modify

Using Access Modifiers

class Invoice {
    constructor(
        readonly client: string,
        private details: string,
        public amount: number
    ) {}

    format(): string {
        return `${this.client} owes $${this.amount} for ${this.details}`;
    }
}

const inv = new Invoice("Mario", "website", 250);
console.log(inv.client);  // ✅ readonly — can read
inv.client = "Luigi";     // ❌ Error — readonly
console.log(inv.details); // ❌ Error — private
inv.amount = 500;         // ✅ public — can modify

Shorthand Constructor

When you use access modifiers in the constructor parameters, TypeScript automatically creates and assigns the properties:

// This shorthand:
class Invoice {
    constructor(
        readonly client: string,
        private details: string,
        public amount: number
    ) {}
}

// Is equivalent to:
class Invoice {
    readonly client: string;
    private details: string;
    public amount: number;

    constructor(c: string, d: string, a: number) {
        this.client = c;
        this.details = d;
        this.amount = a;
    }
}

Key Takeaways

  • public — accessible and modifiable everywhere (default)
  • private — only accessible inside the class
  • readonly — readable everywhere but can't be changed
  • Modifiers in constructor params auto-create properties