Explanation of Getters and Setters in TypeScript

Explanation of Getters and Setters in TypeScript

Hello everyone, in this article we are going to talk about Getter and Setter functions of members in TypeScript programming languages with help of examples.

Let's begin

What is getter and setter in Typescript?

Getters and Setters are very efficient features to control the accesses to the properties of a class in TypeScript. We can control the assignee value to the variable and also we can perform some other functionalities on reading or assiging to a variable.

Getters and Setters provide below benefits for development
  • Validation of the data: We can validate the data on assigning and prevent some unexpected faulty values in centralised way.
  • Abstraction of the property: get and set are abstract methods of the property and these methods are invoking internally. So the operations are happening internally without any external calls.
  • Logging: We can log the property operations for some statistics.
  • Chain operations: We can also call some other methods on reading or writing the property to initialise the chain operations.
  • Encapsulation of the property: Getters and setters help us to encapsulate the property and keep hidden the internal state of the variable.
  • Overriden Return Values: Getter allows us to override the internal value of the property and we can check and return some other overriden values.

Getter

Getter is a dedicated function in TypeScript to get the value of an internal variable of a class. A getter is defining with get keyword and then the name of function without any parameter.

Below you can see an example of Getter function

class Person {
  private _name: string;
  private _surname: string;

  constructor(name: string, surname: string) {
    this._name = name;
    this._surname = surname;
  }

  get name(): string {
    return this._name;
  }
  
  get surname(): string {
    return this._surname;
  }
}

const user = new Person("Burak", "Hamdi");
console.log(user.name); // Burak
console.log(user.surname);  // Hamdi

As you can see above, We are storing the values within internal private variables and we are getting the values with getter functions. As you can see above we called the get function name without paranthesis and we used only the name of name of get function.


Setter

Setter function is changing the value of a function. In here We can make some validations before setting and also allowing the logging and overriding the information before set, or preventing the setting.

Below you can see an example of Setter function

class Employee {
  readonly email_regex: RegExp = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i;
  public errorLogs = "";

  private _email: string;

  constructor(email: string) {
    this._email = email;
  }

  set email(value: string) {
    if ( this.email_regex.test(value) ) {
        this._email = value;
    }
    else{
        this.errorLogs += "Email setting failed\n";
        throw new Error("Email format should be valid.");
    }
  }
}

const employee = new Employee("abcde@gmail.com");
employee.email = "thecodeprogram"; // Error will be thrown here
Program output will throw error

[ERR]: "Executed JavaScript Failed:" 
[ERR]: Email format should be valid. 

As you can see above with setter method we have checked the input value with a regular expression and if it is not valid we prevented to assign and throw an Error. Also we have logged the failure.


That is all for getter and setter in Typescript.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...