Typescript supports public
, private
and protected
modifiers that affect the accessibility of class in different ways.
Access modifiers further a core concept of object oriented programming - ‘encapsulation’. The accessibility of variables and members of a class are driven by modifiers and therefore controlled in the programming flow.
Let’s start with a simple class
example.
|
|
Public modifier
All variables and members are public by default in Typescript.
So, I may as well type -
|
|
.. and no one will leave the chat.
Public variables and members are accessible by anybody outside the class.
|
|
Let’s add and test a method in the class -
|
|
Private modifier
Private modifiers are not accessible outside the class.
|
|
Private variables are accessed through members - if at all they need to be accessed.
|
|
Members behave the same way as variables. Private members are used to perform operations within the class.
|
|
Protected modifier
Protected members can be accessed within the class and by the derived classes. They cannot be accessed outside of that scope.
|
|
Protected variables and members are not accessible from extended-class instances as well as class instances.