Getter and Setter with Typescript

April 26, 2020

Typescript allow defining properties in our classes using getters and setters, it helps to have more control for public fields.

If you comes from C# or Java is the same approach, but in Typescript the get and set are keywords used before the function name. It help us to encapsulate some logic and use private fields for 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, I will use # for private fields, because Typescript 3.8 support it but or use the private keyword as always.

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 with and doesn’t allow set ‘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 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 an 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 for public fields.

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