Sub topic 14
protected: sharing members with subclasses
This chapter assumes you know TypeScript class basics (fields, constructors, methods), the public and private modifiers, and how extends and super work. It covers what protected allows, where it stops, and the rules that cause confusing compiler errors.
What protected means
A protected member is visible inside its own class and inside every subclass. Code outside the class hierarchy cannot see it. It sits between the other two modifiers:
| Modifier | Same class | Subclass | Outside code |
|---|---|---|---|
| `public` | yes | yes | yes |
| `protected` | yes | yes | no |
| `private` | yes | no | no |
Use protected for members that are part of the contract between a base class and its subclasses, but not part of the public API. Typical cases are helper methods meant to be overridden and state that subclasses need to read.
A basic example
class Employee {
constructor(public name: string, protected salary: number) {}
protected bonus(): number {
return this.salary * 0.1;
}
}
class Manager extends Employee {
constructor(name: string, salary: number, private reports: Employee[]) {
super(name, salary);
}
protected override bonus(): number {
return super.bonus() + this.reports.length * 1000;
}
totalPay(): number {
return this.salary + this.bonus();
}
}
const manager = new Manager("Ada", 100000, []);
console.log(manager.totalPay()); // 110000
// manager.salary; // Error: Property 'salary' is protected and only accessible within class 'Employee' and its subclasses.
// manager.bonus(); // Error: Property 'bonus' is protected and only accessible within class 'Manager' and its subclasses.Manager reads this.salary and calls super.bonus() freely. The public method totalPay() is the only way for outside code to get at the result.
The instance rule
Inside a subclass, you can access a protected member only through an instance of that subclass (or one of its own subclasses). You cannot access it through a base-class instance or through a sibling class instance. TypeScript follows the same rule as Java and C#.
class Base {
protected secret = 42;
}
class Left extends Base {
sameType(other: Left): number {
return other.secret; // OK: other is a Left
}
baseType(other: Base): number {
// return other.secret;
// Error: Property 'secret' is protected and only accessible through an instance of class 'Left'. This is an instance of class 'Base'.
return 0;
}
}
class Right extends Base {}
const left = new Left();
console.log(left.sameType(new Left())); // 42
// left.sameType(new Right()); // Error only if Right is structurally different from LeftThe reasoning is that a Base parameter could actually be a Right, and Left has no claim on Right's protected state. If a subclass needs to read this state from arbitrary base instances, add a protected static helper on the base class, or expose a public accessor.
Changing visibility in a subclass
A subclass can make an inherited protected member public. It cannot make a public member protected.
class Base {
protected m = 10;
public n = 20;
}
class Derived extends Base {
m = 15; // OK: omitting the modifier means public, so protected is widened
// protected n = 25;
// Error: Class 'Derived' incorrectly extends base class 'Base'.
// Property 'n' is protected in type 'Derived' but public in type 'Base'.
}
console.log(new Derived().m); // 15Widening is allowed because a Derived must stay usable wherever a Base is expected, and exposing more never breaks that. Narrowing would break it, because code holding a Base reference could call a member that no longer exists publicly on the object. Widening is often done by accident when you redeclare a member and forget the modifier. Write protected explicitly on every override to avoid this.
Protected constructors
A constructor can also be protected. The class cannot be instantiated from outside its hierarchy, but subclasses can call super(). This gives you a base class that is not abstract but should only be created through a subclass or a static factory.
class Notifier {
protected constructor(protected readonly channel: string) {}
protected format(message: string): string {
return `[${this.channel}] ${message}`;
}
send(message: string): void {
console.log(this.format(message));
}
}
class EmailNotifier extends Notifier {
constructor() {
super("email");
}
protected override format(message: string): string {
return super.format(message).toUpperCase();
}
}
new EmailNotifier().send("hello"); // [EMAIL] HELLO
// new Notifier("sms"); // Error: Constructor of class 'Notifier' is protected and only accessible within the class declaration.This example also shows protected inside a parameter property, which declares and assigns the field in one step.
Runtime behavior
protected exists only in the type system. The compiler erases it, and the emitted JavaScript has ordinary properties. Any code can read (manager as any).salary at runtime, and Object.keys lists protected fields. If you need real runtime privacy, use #private fields, which a later chapter covers. Remember that #private members are not visible to subclasses at all.
Common errors
- "Property is protected and only accessible within class X and its subclasses." You accessed the member from outside the hierarchy. Add a public method or getter, or reconsider the design.
- "...only accessible through an instance of class 'Left'." You accessed a protected member through a base or sibling type. Change the parameter type to the subclass, or expose the data differently.
- "Class incorrectly extends base class." A subclass narrowed a member from public to protected. Keep it public.
- Accidentally public override. You overrode a protected method and left off the modifier. Write
protected overrideevery time.
Exercise
Given class Shape { protected id = 1; } and class Square extends Shape { sameId(other: Shape): boolean { return this.id === other.id; } }, why does this fail to compile, and what is the smallest change that fixes it?
Show answer
Inside Square, a protected member can be accessed only through an instance of Square (or its subclasses), and other is typed as Shape. The smallest fix is to change the parameter type to Square: sameId(other: Square): boolean. Alternatives are to add a public getId() method on Shape, or to make id public.
Exercise
A base class declares protected log(msg: string): void. A subclass redeclares it as log(msg: string): void { ... } with no modifier. What is the effect, and how do you avoid it?
Show answer
The subclass method is public, because omitting the modifier means public. TypeScript allows this because widening visibility is safe, so no error appears. Outside code can now call log on the subclass. Avoid it by writing protected override log(msg: string): void.