I wonder if there are any syntax/design patterns to achieve the following:
Consider a class like this:
Class myClass{
private a: int;
private b: int;
private c: int;
private d: int;
...
//20 more private variables
}
I basically want to do this:
const x = new myClass().a(32).b(34).c(56);
which would basically create a class whose a=32, b=34, c=56;
The only way I know is to create public functions:
Class myClass{
public a(val: int){
a = val;
return this;
}
public b(val: int){
b = val;
return this;
}
public c(val: int){
c = val;
return this;
}
...//for 20 more rows :-(
}
As you can see this would be very repetitive, yes ofcourse I could do this:
Class myClass{
set properties({a, b, c, d, e, ...//more vars}: any) {
this.a = a;
this.b = b;
//others
}
}
But, I'd like to achieve this syntax:
const x = new myClass().a(32).b(34).c(56);
Because, it's much cleaner and makes sense for my usecase, where I'll only ever be overriding a handful of values.
Is there any way in nodejs/typescript I can achieve this avoiding the constrains mentioned above?