Getter and Setter with Typescript

The encapsulation is an important 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 how to use get and setter for encapsulating logic for public fields and keep the state with a private field.

The 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 come to help us in our code, defining 2 functions with get and set keyword before the function name.

the location function with the keyword get must to have a 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 be used to store it into the private field location. In our scenery, we take the value parameter and checks 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.