Understanding private
When a member is marked private
, it cannot be accessed from outside of its containing class. For example:
class Animal { private name: string; constructor(theName: string) { this.name = theName; } } new Animal("Cat").name; // Error: 'name' is private;
TypeScript is a structural type system. When we compare two different types, regardless of where they came from, if the types of all members are compatible, then we say the types themselves are compatible.
However, when comparing types that have private
and protected
members, we treat these types differently. For two types to be considered compatible, if one of them has a private
member, then the other must have a private
member that originated in the same declaration. The same applies to protected
members.
Let’s look at an example to better see how this plays out in practice:
class Animal { private name: string; constructor(theName: string) { this.name = theName; } } class Rhino extends Animal { constructor() { super("Rhino"); } } class Employee { private name: string; constructor(theName: string) { this.name = theName; } } let animal = new Animal("Goat"); let rhino = new Rhino(); let employee = new Employee("Bob"); animal = rhino; animal = employee; // Error: 'Animal' and 'Employee' are not compatible
In this example, we have an Animal
and a Rhino
, with Rhino
being a subclass of Animal
. We also have a new class Employee
that looks identical to Animal
in terms of shape. We create some instances of these classes and then try to assign them to each other to see what will happen. Because Animal
and Rhino
share the private
side of their shape from the same declaration of private name: string
in Animal
, they are compatible. However, this is not the case for Employee
. When we try to assign from an Employee
to Animal
we get an error that these types are not compatible. Even though Employee
also has a private
member called name
, it’s not the one we declared in Animal
.
Please login to continue.