Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getter/Setter In Typescript

Tags:

typescript

I was following a tutorial on Typescript Classes and the person teaching created a class and some setter/getter methods.But when i read Typescript Documentation the approach was somewhat different. Can someone help me understand the difference between both approaches.

Approach 1:

class Student {
private _name: string;

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

getName = (): string => {
    return this._name;
}

setName = (name: string) => {
    this._name = name;
}
}

Approach 2:

class Student {
private _name: string;

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

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


public set name(value: string) {
    this._name = value;
}
}

Have a look. In Approach 1 we write getter/setter as normal functions But in Approach 2 the keyword get/set is used. Can someone help me understand the difference between both approaches.

like image 249
Raj Thakur Avatar asked Aug 02 '18 06:08

Raj Thakur


1 Answers

The difference in the way you use them. In the first case you need to explictly call the get/set methdods. In the second you can use name like an actual field on the class and the runtime will call the get/set accessors automatically.

Consider the simple example of appending a character to the name:

Approach 1

let s = new Student();
s.setName(s.getName() + "A") // we need to explicitly call the get/ set methods

Approach 2

let s = new Student();
s.name += "A" // we can use += and the get/set accessors will get called for us

Behind the scene the get/set accessor approach (approach 2) will use Object.defineProperty

like image 113
Titian Cernicova-Dragomir Avatar answered Oct 23 '22 21:10

Titian Cernicova-Dragomir