Protected modifier in TypeScript
Private properties and methods are not inherited by children. Sometimes, however, we want a property or method to be inaccessible from the outside, but inherited by children. In this case, the protected modifier should be used.
Let's try it in practice. Let's declare in our class User the method cape as protected using the modifier protected:
class User {
protected cape(str: string) {
return str[0].toUpperCase() + str.slice(1);
}
}
Let's create a class Student that inherits from the class User:
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
}
Let's add a method that displays the name:
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
public showName(): string {
return this.name;
}
}
Now we use the protected parent method inside the child method:
class Student extends User {
private name: string;
constructor(name: string) {
super();
this.name = name;
}
public showName(): string {
return this.cape(this.name); // we use the parent method
}
}
Let's create an object of our class:
let student: Student = new Student('john');
Let's use the method to output the student:
console.log(student.showName());
But trying to call the cape method from outside the class will result in an error:
console.log(student.cape('test')); //
The following class is given:
class User {
protected name: string;
protected surn: string;
constructor(name: string, surn: string) {
this.name = name;
this.surn = surn;
}
}
Inherit the Employee class from this class, which will add a protected salary property, as well as getters for all properties, both its own and inherited.