Javatpoint Logo
Javatpoint Logo

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.

TypeScript Access Modifiers

The TypeScript access modifiers are of three types. These are:

  1. Public
  2. Private
  3. Protected.

Understanding all TypeScript access modifiers

Let us understand the access modifiers with a given table.

Access Modifier Accessible within class Accessible in subclass Accessible externally via class instance
Public Yes Yes Yes
Protected Yes Yes No
Private Yes No No

Public

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.

Example

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.

Output:

TypeScript Access Modifiers

Private

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.

Example

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.

Output:

TypeScript Access Modifiers

Protected

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.

Example

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.

Output:

TypeScript Access Modifiers

Readonly Modifier

  • We can make the properties of the class, type, or interface readonly by using the readonly modifier.
  • This modifier needs to be initialized at their declaration time or in the constructor.
  • We can also access readonly member from the outside of a class, but its value cannot be changed.

Example

Output:

TypeScript Access Modifiers



Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA