Sub topic 14
`protected`: Sharing Members with Subclasses
Assume you know basic TypeScript types, JavaScript classes, and the extends keyword. This chapter focuses on how a subclass can use selected members from its parent class without exposing those members to ordinary callers.
What `protected` means
protected is an access modifier for a class member. A protected field or method can be used inside the class that declares it and inside subclasses. Code outside that class hierarchy cannot access it directly.
Use protected when a parent class owns an implementation detail that subclasses need to extend or customize. Use private when even subclasses should not access the member.
class Employee {
constructor(
public readonly name: string,
protected salary: number
) {}
protected calculateBonus(): number {
return this.salary * 0.1;
}
public totalPay(): number {
return this.salary + this.calculateBonus();
}
}
class Manager extends Employee {
constructor(
name: string,
salary: number,
private readonly reportCount: number
) {
super(name, salary);
}
public override totalPay(): number {
const managerBonus = this.reportCount * 1_000;
return super.totalPay() + managerBonus;
}
}
const manager = new Manager("Ada", 100_000, 2);
console.log(manager.totalPay()); // 112000
// manager.salary;
// Error: Property 'salary' is protected and only accessible
// within class 'Employee' and its subclasses.
// manager.calculateBonus();
// Error: Property 'calculateBonus' is protected.The Manager subclass can use salary through inherited behavior such as super.totalPay(). It cannot expose salary directly to callers. The public method totalPay provides the supported API.
Choosing an access modifier
| Modifier | Declaring class | Subclasses | Outside code |
|---|---|---|---|
| `public` | Yes | Yes | Yes |
| `protected` | Yes | Yes | No |
| `private` | Yes | No | No |
Access modifiers are checked by TypeScript during compilation. They do not automatically create runtime security. JavaScript emitted from TypeScript can still contain an ordinary property that code may reach through untyped operations.
A protected method as an extension point
A protected method often gives subclasses a controlled place to change behavior:
class Report {
protected formatTitle(title: string): string {
return title.toUpperCase();
}
public render(title: string): string {
return `Report: ${this.formatTitle(title)}`;
}
}
class PlainReport extends Report {
protected override formatTitle(title: string): string {
return title;
}
}
console.log(new PlainReport().render("Sales"));
// Report: Salesrender keeps the public workflow stable. The subclass changes only the formatting step.
Exercise
When should you choose protected instead of private?
Show answer
Choose protected when subclasses must use or override the member. Choose private when only the declaring class should access it.