TypeScript - 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.

class class_name {
    // Define private variable here.

    // Defining the getter
    get getter_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 class
class Person {
    // Defining the private field
    private Name: string;

    // Defining the constructor
    constructor(Name: string) {
        this.Name = Name;
    }

    // Defining the getter
    get SName(): string {
        return this.Name;
    }
}

// Creating an instance of the Person class
const person = new Person("John");
console.log(person.SName); // Outputs: John

On compiling, it will generate the following JavaScript code.

// Defining the Person class
class Person {
    // Defining the constructor
    constructor(Name) {
        this.Name = Name;
    }
    // Defining the getter
    get SName() {
        return this.Name;
    }
}
// Creating an instance of the Person class
const person = new Person("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.
class Temperature {
    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.
    get fahrenheit(): number {
        return (this.celsius * 9 / 5) + 32;
    }
}

// Create an instance of the Temperature class with a temperature of 25 degrees Celsius.
const temp = new Temperature(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.
class Temperature {
    // Define a constructor that initializes the Celsius property.
    constructor(celsius) {
        this.celsius = celsius;
    }
    // Define a getter fahrenheit that returns the temperature in Fahrenheit.
    get fahrenheit() {
        return (this.celsius * 9 / 5) + 32;
    }
}
// Create an instance of the Temperature class with a temperature of 25 degrees Celsius.
const temp = new Temperature(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.

class class_name {
    // Define private variable here.

    // Defining the setter
    set setter_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 method
class TextContainer {
    // Define a private property
    private _content: string = '';

    // Setter method
    set content(value: string) {
        this._content = value.trim().toLowerCase();
    }

    // Getter method
    get content(): string {
        return this._content;
    }
}

// Create an instance of the class and set the content
const text = new TextContainer();
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 method
class TextContainer {
    constructor() {
        // Define a private property
        this._content = '';
    }
    // Setter method
    set content(value) {
        this._content = value.trim().toLowerCase();
    }
    // Getter method
    get content() {
        return this._content;
    }
}
// Create an instance of the class and set the content
const text = new TextContainer();
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.

Advertisements