Javatpoint Logo
Javatpoint Logo

TypeScript Access Modifiers

  • Access modifiers give the direct access control to the member of a class. These class members are the functions and properties. The class members can only be used inside its own class, they could be used anywhere outside the class, or they could be used within its child or derived class.
  • These modifiers increase the security of the class members and prevent them from invalid use.
  • The class used access modifiers to control the visibility of its data members.
  • If the class does not have to be set any access modifier, By default TypeScript sets public access modifier to all class members.
  • The Typescript access modifiers can be categorized into three types. These are: public, private and protected.

Understanding all TypeScript access modifiers

Let's understand the access modifiers by a simple 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 of a class are public. The public data member can be accessed anywhere without any restriction.

Example

In the above example, studCode is declared as public and studName is declared without a modifier, so TypeScript treats them as public by default. Since data members are public, they can be accessible outside of the class using an object of the class.

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 declared as private, and studName is declared without a modifier, so TypeScript treats them as public by default. If we access the private member outside of the class, it will give a compile error.

Protected

A Protected access modifier can be accessed only within the class and its subclass. It cannot be accessed outside of the class in which it is containing.

Example

Output:

My unique code: 1, my name: JoeRoot and I am in CS Branch.
undefined

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 because Person class derives from Student class.

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.
  • A Readonly member can be accessed from outside of the class, but its value cannot be changed.

Example





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA