TypeScript Access Modifiers
An access modifier controls where a class member can be reached from. TypeScript checks private, protected, and readonly members at compile time.
Read a private field inside the class
The code field is private. The public report method reads it from inside the class.
class Vault {
private code: number;
constructor(code: number) {
this.code = code;
}
report(): void {
console.log(this.code);
}
}
const vault = new Vault(1234);
vault.report();Read a private field from outside
Code outside the class tries to read the private field. The compiler refuses the read.
class Vault {
private code: number;
constructor(code: number) {
this.code = code;
}
}
const vault = new Vault(1234);
console.log(vault.code);Change a readonly field
The title field is readonly. Code after construction tries to assign a new title.
class Book {
readonly title: string;
constructor(title: string) {
this.title = title;
}
}
const book = new Book("Dune");
book.title = "Emma";Read a protected field in a subclass
The name field is protected. The subclass method reads it through this.
class Person {
protected name: string;
constructor(name: string) {
this.name = name;
}
}
class Employee extends Person {
greet(): void {
console.log("Hello, " + this.name);
}
}
const worker = new Employee("Ada");
worker.greet();Example
class Account {
private balance: number;
readonly owner: string;
constructor(owner: string, balance: number) {
this.owner = owner;
this.balance = balance;
}
report(): void {
console.log(this.owner);
console.log(this.balance);
}
deposit(amount: number): void {
this.balance = this.balance + amount;
}
}
const account = new Account("Ada", 100);
account.report();
account.deposit(25);
account.report();Key points
- A member with no modifier is public and can be reached from anywhere.
- A private member can be reached only inside its own class.
- A protected member can be reached inside its class and inside subclasses.
- A readonly field can be set during construction and never after.
- The compiler refuses code that breaks a modifier rule.
In this example, the Account class holds a private balance and a readonly owner. The constructor sets both fields. The public report method reads the private balance from inside the class. The deposit call raises the balance, and the second report shows the new total.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท TypeScript Playground
Exercise
Which modifier allows access inside a class and its subclasses, but not outside?