Accessors

Accessors in TypeScript provides a way to access and set the value of the class members using the getter and setter methods. They control how class members are accessed to read or write their values.

Accessors are useful for achieving encapsulation in TypeScript, which restricts access to class members only to the member functions of the class, preventing unauthorized access via third parties.

TypeScript supports the followings to access and change class members:

  • getters
  • setters

Getters in TypeScript

Getters are used to access the values of class members and manage how these values are accessed outside of the class. They can be created using the ‘get’ keyword.

Syntax

You can follow the syntax below to use getters in TypeScript.

classclass_name{// Define private variable here.// Defining the gettergetgetter_name(): return_type {// Return variable value}}let val = class_name.getter_name;

In the above syntax, the method_name method is a static method, which can take multiple parameters and return a value.

To access the value using the getter, we can use the class name followed by a dot followed by the getter method name.

Example

In the example below, we have defined the Person class, which contains the ‘Name’ private variable. It also contains the constructor() method which initializes the value of the ‘Name’ variable.

// Defining the Person classclassPerson{// Defining the private fieldprivate Name:string;// Defining the constructorconstructor(Name:string){this.Name = Name;}// Defining the gettergetSName():string{returnthis.Name;}}// Creating an instance of the Person classconst person =newPerson("John");console.log(person.SName);// Outputs: John

On compiling, it will generate the following JavaScript code.

// Defining the Person classclassPerson{// Defining the constructorconstructor(Name){this.Name = Name;}// Defining the gettergetSName(){returnthis.Name;}}// Creating an instance of the Person classconst person =newPerson("John");console.log(person.SName);// Outputs: John

Output

John

Example

In the code below, the Temperature class contains the ‘celsius’ private variable. The constructor() method initializes the value of the ‘celsius’ variable.

// Define a class Temperature with a property Celsius of type number.classTemperature{private celsius:number;// Define a constructor that initializes the Celsius property.constructor(celsius:number){this.celsius = celsius;}// Define a getter fahrenheit that returns the temperature in Fahrenheit.getfahrenheit():number{return(this.celsius *9/5)+32;}}// Create an instance of the Temperature class with a temperature of 25 degrees Celsius.const temp =newTemperature(25);console.log("The Fahrenheit value is: "+ temp.fahrenheit);// Outputs: 77

On compiling, it will generate the following JavaScript code.

// Define a class Temperature with a property Celsius of type number.classTemperature{// Define a constructor that initializes the Celsius property.constructor(celsius){this.celsius = celsius;}// Define a getter fahrenheit that returns the temperature in Fahrenheit.getfahrenheit(){return(this.celsius *9/5)+32;}}// Create an instance of the Temperature class with a temperature of 25 degrees Celsius.const temp =newTemperature(25);console.log("The Fahrenheit value is: "+ temp.fahrenheit);// Outputs: 77

Output

The Fahrenheit value is: 77

Setters in TypeScript

In TypeScript, setters are used to set the value of class members without accessing them outside of the class. They use the ‘set’ keyword to define the setter method.

Syntax

You can follow the syntax below to use setters in TypeScript.

classclass_name{// Define private variable here.// Defining the settersetsetter_name(val: type){// Set variable value}}

class_name.setter_name = val;

In the above syntax, we have used the ‘set’ keyword followed by ‘setter_name’ to define a setter. It takes only a single value as a parameter and uses it inside the setter method to change the value of any private class variables.

To use the setter method, you need to use the class name followed by a dot followed by the setter method name and assign a value to it.

Example

In the code below, we have defined the TextContainer class, which contains the ‘_content’ private variable to store the text.

// Define a class with a private property and a getter/setter methodclassTextContainer{// Define a private propertyprivate _content:string='';// Setter methodsetcontent(value:string){this._content = value.trim().toLowerCase();}// Getter methodgetcontent():string{returnthis._content;}}// Create an instance of the class and set the contentconst text =newTextContainer();
text.content ="  Hello, WORLD!  ";console.log(text.content);// Outputs: hello, world!

On compiling, it will generate the following JavaScript code.

// Define a class with a private property and a getter/setter methodclassTextContainer{constructor(){// Define a private propertythis._content ='';}// Setter methodsetcontent(value){this._content = value.trim().toLowerCase();}// Getter methodgetcontent(){returnthis._content;}}// Create an instance of the class and set the contentconst text =newTextContainer();
text.content ="  Hello, WORLD!  ";console.log(text.content);// Outputs: hello, world!

Output

hello, world!

It is very important to use accessors to achieve encapsulation in TypeScript. You can also create multiple getter and setter methods in a single class.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *