Access Modifiers
public, private, protected, and readonly — controlling visibility.
14 minLevel 7 of 20
public, private, protected
Access modifiers control who can touch members:
- public — anywhere (default)
- private — only inside the class
- protected — class + subclasses
Nest services keep repositories private readonly so controllers cannot reach around the API.
Visibility
class BankAccount {
constructor(private balance: number) {}
deposit(n: number) { this.balance += n; }
getBalance() { return this.balance; }
}
const a = new BankAccount(100);
a.deposit(20);
console.log(a.getBalance());
// console.log(a.balance); // compile-time errorprotected for inheritance
protected lets subclasses reuse internals without making them public API.
protected
class Shape {
constructor(protected color: string) {}
}
class Circle extends Shape {
describe() { return `${this.color} circle`; }
}
console.log(new Circle("red").describe());readonly with private
Combine private readonly for injected deps — assign once in the constructor, never reassigned, never exposed.
Nest style
class OrdersService {
constructor(private readonly repo: { all(): string[] }) {}
list() { return this.repo.all(); }
}
console.log(new OrdersService({ all: () => ["o1"] }).list());Check your understanding
5 questionsQuestion 1 of 5
Score: 0
Multiple choice