TypeScript Access Modifiers
Like other programming languages, Typescript allows us to use access modifiers at the class level. It gives direct access control to the class member. These class members are functions and properties. We can use class members inside its own class, anywhere outside the class, or within its child or derived class.
The access modifier increases the security of the class members and prevents them from invalid use. We can also use it to control the visibility of data members of a class. If the class does not have to be set any access modifier, TypeScript automatically sets public access modifier to all class members.
The TypeScript access modifiers are of three types. These are:
Understanding all TypeScript access modifiers
Let us understand the access modifiers with a given table.
In TypeScript by default, all the members (properties and methods) of a class are public. So, there is no need to prefix members with this keyword. We can access this data member anywhere without any restriction.
In the above example, studCode is public, and studName is declared without a modifier, so TypeScript treats them as public by default. Since data members are public, they can be accessed outside of the class using an object of the class.
The private access modifier cannot be accessible outside of its containing class. It ensures that the class members are visible only to that class in which it is containing.
In the above example, studCode is private, and studName is declared without a modifier, so TypeScript treats it as public by default. If we access the private member outside of the class, it will give a compile error.
A Protected access modifier can be accessed only within the class and its subclass. We cannot access it from the outside of a class in which it is containing.
In the above example, we can't use the name from outside of Student class. We can still use it from within an instance method of Person class because Person class derives from Student class.