The TypeScript accessor provides us with a way to implement encapsulation.
In simple terms, encapsulation
hides the data members so that they can only be accessed by the member functions of the same class.
The code snippet below provides an example of encapsulation
.
class User{firstname:stringlastname:stringfullName(){return this.firstname + " " + this.lastname}}let user1 = new User();//setting the firstname and lastname from outside classuser1.firstname = "John"user1.lastname = "Doe"console.log(user1.fullName())
In the code above:
Lines to define the User
class, which contains firstname
and lastname
as member variables, and fullname()
as a member function.
Line creates an instance of the User
class and stores it in the user1
variable.
Lines to set the values for member variables firstname
and lastname
from outside the class.
We allow external changes to the data here, but sometimes we may not want to expose the data. In that case, we use the
encapsulation
concept.
Typescript accessor provides two methods to perform get and set operations.
Getter
: This method is used to retrieve a value and can be invoked through the get
keyword.Setter
: This method is used to set a value and can be invoked through the set
keyword.We will modify the User
class example above with getter
and setter
.
class User{private firstname:stringprivate lastname:stringset fname(f:string){this.firstname = f.toUpperCase();}set lname(f:string){this.lastname = f.toUpperCase();}get fullName(){return this.firstname + " " + this.lastname}}let user1 = new User();user1.fname = "John";user1.lname = "Doe"console.log(user1.fullName)
The changes made to the code are as follows:
In lines to , the access type of the member variables is now private
.
Lines to define two setter
methods to set values for member variables. We can modify the data taken from the user in setter
methods. Here, we convert names to uppercase. We also define a getter
method to get fullname
.
Lines to use setter
methods to set the values for member variables. We don’t need to call the method here; instead, we can set values as variables.
Line uses the getter
method to print fullname
to the console.
If we try to set values for private
member variables, the TypeScript compiler will throw an error.
In the following code snippet, we try to set the value for the private member variable firstname
in line . The compiler will throw the Property 'firstname' is private and only accessible within class 'User'
error.
class User{private firstname:stringprivate lastname:stringset fname(f:string){this.firstname = f.toUpperCase();}set lname(f:string){this.lastname = f.toUpperCase();}get fullName(){return this.firstname + " " + this.lastname}}let user1 = new User();//trying to set value "John" to private member variable firstnameuser1.firstname = "John"