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
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.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With