What is TypeScript accessor?
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
Userclass, which containsfirstnameandlastnameas member variables, andfullname()as a member function. -
Line creates an instance of the
Userclass and stores it in theuser1variable. -
Lines to set the values for member variables
firstnameandlastnamefrom 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
encapsulationconcept.
Getter and setter
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 thegetkeyword.Setter: This method is used to set a value and can be invoked through thesetkeyword.
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
settermethods to set values for member variables. We can modify the data taken from the user insettermethods. Here, we convert names to uppercase. We also define agettermethod to getfullname. -
Lines to use
settermethods 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
gettermethod to printfullnameto 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"