

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Classes
incomplete
2: Private Class Members
incomplete
3: TypeScript Public and Private
incomplete
4: Protected Data Members
incomplete
5: Abstract Classes and Methods
incomplete
6: Classes Implement Interfaces
incomplete
7: Classes vs. Interfaces and Types
incomplete
8: The 'this' Type
incomplete
9: Parameter Properties
incomplete
Back
ctrl+,
Next
ctrl+.
This lesson's interactive features are locked, please to keep using them
The protected keyword is unique to TypeScript in that it's not part of the EcmaScript standard. It allows you to define members that are accessible within the class and its subclasses, but not from outside the class. It's like "private but also accessible to subclasses".
class Character {
protected health: number;
constructor(health: number) {
this.health = health;
}
protected takeDamage(amount: number): void {
this.health -= amount;
if (this.health < 0) {
this.health = 0;
}
}
}
class Fighter extends Character {
constructor(health: number) {
super(health);
}
public fight(damage: number): void {
// Can access protected members from the parent class
this.takeDamage(damage);
console.log(`Fighter took ${damage} damage. Health: ${this.health}`);
}
}
const fighter = new Fighter(100);
fighter.fight(30);
// Error: Property 'health' is protected and only accessible within class 'Character' and its subclasses
console.log(fighter.health);
// Error: Property 'takeDamage' is protected and only accessible within class 'Character' and its subclasses
fighter.takeDamage(10);
The protected keyword does not have a native JavaScript alternative. I personally don't use it very often. I tend to use # private fields whenever possible, or just leave them public if subclasses need access.
A RegularCustomer is just a more specific type of Customer where their balance needs to be accessible via the getBalance method.
Notice that the getBalance method is trying to access a private field.