What is the best way to generalize the setters and getters in this class:
class A {
constructor() {
this._foo = new Foo();
this._bar = new Bar();
}
get foo() {
return this._foo;
}
set foo(value) {
if (value instanceof Foo)
this._foo = value;
else
this._foo = Object.assign(new Foo(), value);
}
get bar() {
return this._bar;
}
set bar(value) {
if(value instanceof Bar)
this._bar = value;
else
this._bar = Object.assign(new Bar(), value);
}
}
Edit
Yes, the question can be opinion based and can be get around with a typed language. But how to resolve it in es6 for existing projects without migration option?
I need this setters to define the type of members after deserializing a json document saved in database :
{
"foo" :{"x":0,"y":0,"z":0},
"bar" : {"propA": "valueA", "propB": "valueB"}
}