Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript getter/setter naming convention

I come from a Java background and I defaulted to using getter/setter naming conventions in my Typescript/Angular component classes familiar to me.

getFoo()

setFoo()

However, it seems that this may not be the best practice, but rather I should use the convention

get foo()

set foo()

Questions

  • Is this purely cosmetic? Any benefits? I don't understand why this would be favored since it is, to my understanding, inconsistent with the naming convention used for other methods.
  • Is there a formal style guide recommending this practice?
like image 574
The Gilbert Arenas Dagger Avatar asked Jun 27 '19 11:06

The Gilbert Arenas Dagger


2 Answers

We can use get, set where we need to implement some constraints when a value is accessed.

From Typescript documentation:

TypeScript supports getters/setters as a way of intercepting accesses to a member of an object. This gives you a way of having finer-grained control over how a member is accessed on each object.

Example:

class StudentMark {
    isPass: boolean;
    _mark: Mark;
    set mark(value: Mark) {
        if (value.subject1 > 35 && value.subject2 > 35&& value.subject3 > 35) { 
             this.isPass = true;
        } else {
             this.isPass = false;
        }
        this._mark = value;
    }
   get mark(): Mark {
       return this._mark;
   }
}

Here, whenever we set the mark, the pass will be updated. No, need to update it separately. In this, type of cases get, set will be useful.

Suffix of get and set should have same name. And we can access it by only calling the name itself. Example, mark from above code.

For, more about get, set visit typescript documentation.

like image 66
madhan kumar Avatar answered Nov 15 '22 06:11

madhan kumar


type-script is superset of java-script and all of language syntax very similar of ECMAScript standard because programmer feeling better writing java-script application.

SET, GET property on TS & JS very similar

JS

class JSExample {
    constructor() {
        this._val = "V";
    }
    get val() {
        return this._val;
    }
    set val($v) {
        this._val = $v;
    }
}

TS

class TSExample {
    _val = "V";

    get val(): string {
        return this._val;
    }
    set val($v: string) {
        this._val = $v;
    }
}
like image 45
Moslem Shahsavan Avatar answered Nov 15 '22 05:11

Moslem Shahsavan