Dany Paredes
Dany Paredes | Javascript / Web

Dany Paredes | Javascript / Web

Getter and Setter with Typescript

Getter and Setter with Typescript

Dany Paredes's photo
Dany Paredes
·Apr 25, 2020·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

The encapsulation is an essential part of OOP, and Typescript support gets and sets keywords for members of classes.

The encapsulation can be used with the get and set keywords before a function name, then using it. We can encapsulate some logic and use our private fields to manage the state.

I will do a small example of using get and setter for encapsulating logic for public fields and keeping the state with a private field.

An example is the class Student with a private location private field to save the location.

Typescript 3.8 allows creating private fields using # or with the private keyword.

class Student {
    #location: string;
    public name: string;
    constructor(name:string, location: string   ) {
        this.name = name;
        this.#location = location
    }
}

We want to add a public field to show the Student location and validation that doesn't permit a set of NY as location.

The get and setters help us in our code, defining two functions with getting and keywords word before the function name.

The location function with the keyword get must return the value stored into the private field, in our case, this.#location field.

The location function with the set keyword must have a parameter value and store it into the private field location. In our scenery, we take the value parameter and check if it equals NY, then raise an error or, if not, set it to this.#location private field.

class Student {
    #location: string;
    public name: string;
   get location()  {
        return this.#location;
    }
    set location(value){
        if(value === "NY") {
            throw new Error(`${value} is invalid.`)
        } else {
        this.#location = value;
        }
    }
    constructor(name:string, location: string   ) {
        this.name = name;
        this.#location = location
    }
}

If create a object with NY location, it will raise an error.

let demoUser = new Student('Dany', 'NY');
console.log(demoUser .location);
nodemon] starting `node estudiante.js`
C:\Users\dany\Desktop\curso\estudiante.js:27
            throw new Error(`${value} is invalid.`);
            ^

Error: NY is invalid.
    at Student.set location [as location] (C:\Users\dany\Desk
top\curso\estudiante.js:27:19)

It is an easy way to have a validation encapsulated into the public field assignment.

Hopefully, that will give you a bit of help with getter and setter in Typescript. If you enjoyed this post, share it.

Photo by Keagan Henman on Unsplash

 
Share this