To add a protected property to a class in TypeScript, we need to use the protected
access modifier in TypeScript. A protected
property or method can be accessed within the class and its subclasses but not outside of the class.
Consider the example below:
index.ts655 chars31 lines
In the example above, we have defined a Person
class with a protected
age
property. We have also defined a Student
class that extends the Person
class and has a private grade
property. Both classes have a describe
method that logs a description to the console. Notice that the Student
class is able to access the age
property of the Person
class because it is protected
.
By using the protected
access modifier, we can restrict access to certain properties or methods of a class and ensure that they are only accessible within the class and its subclasses.
gistlibby LogSnag