Protected Data Members
What
The protected modifier is a middle ground between public and private. Protected members are accessible within the class they are defined in and any of its subclasses, but remain private to everything else.
How
Use the protected keyword before a member name:
class Character {
protected health: number = 100;
}
class Fighter extends Character {
attack() {
this.health -= 10; // OK: Subclass can access protected member
}
}
const f = new Fighter();
// Error: Property 'health' is protected
console.log(f.health);
Why
protected is essential for inheritance. it allows you to share internal state and utility methods with specialized versions of a class while still maintaining a clean, encapsulated public API.
Summary
Use protected when you want to allow subclasses to interact with a property while hiding it from external users.