Protected class members
When using inheritance, it is sometimes logical to mark certain functions and properties as accessible only within the class itself, or accessible to any class that is derived from it. Using the private keyword, however, will not work in this instance, as a private class member is hidden even from derived classes. TypeScript introduces the protected keyword for these situations. Consider the following two classes:
class ClassUsingProtected { protected id : number | undefined; public getId() { return this.id; } } class DerivedFromProtected extends ClassUsingProtected { constructor() { super(); this.id = 0; } }
We start with a class named ClassUsingProtected that has an id property that is marked as protected, and a public function named getId. Our next DerivedFromProtected class, inherits from ClassUsingProtected, and has a single constructor function. Note that within this constructor function, we are calling this.id = 0, in order to set the protected id property to 0. Again, a derived class has access to protected member variables. Now, let's try to access this id property outside of the class, as follows:
var derivedFromProtected = new DerivedFromProtected(); derivedFromProtected.id = 1; console.log(`getId returns: ${derivedFromProtected.getId()}`);
Here, we create an instance of the DerivedFromProtected class, and attempt to assign a value to its protected id property. The compiler will generate the following error message:
error TS2445: Property 'id' is protected and only accessible within class 'ClassUsingProtected' and its subclasses.
So, this id property is acting like a private property outside of the class ClassUsingProtected, but still allows access to it within the class, and any class derived from it.