Lesson 17 / 26
Access Modifiers & readonly
Control visibility with public, private and protected.
public / private / protected
public (default) is visible everywhere, private only inside the class, protected inside the class and its subclasses.
class Account {
public owner: string;
private balance: number;
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
}
}
const acc = new Account("Ada", 500);
console.log(acc.balance);
// Error: Property 'balance' is private and only accessible within class 'Account'.Parameter properties
Adding a modifier directly to a constructor parameter declares and assigns the property in one step.
class Account {
constructor(
public owner: string,
private balance: number,
readonly openedOn: Date = new Date()
) {}
}
// equivalent to writing the fields + this.x = x manuallyreadonly on class fields
A readonly field can be set in the constructor but never reassigned afterward — good for IDs and creation timestamps.
Quick check: Which modifier allows access from a subclass but not from outside code?
- public
- private
- protected
Answer
protected — protected members are visible in the declaring class and its subclasses, but not to outside code.