I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters.
function bar() {
let p = 0;
function f() {
}
f.prop = function(d) {
return !arguments.length ? p : (p = d, f);
}
return f;
}
With this approach, I can easily create and set values like const b = bar().prop(2)
, where b
represents the function and allows for additional chained statements. To retrieve the property, I simply use b.prop()
, which cannot be further chained.
As I attempt to convert this functionality into TypeScript, I came across a solution that provides proper typing but appears somewhat convoluted.
p.prop = (...args: [number?]) => !args.length ? p : (p = args[0]!, f);
This complexity is heightened when the argument can take multiple types.
p.prop = (...args: [(number | boolean)?]) => !args.length ? p : (p = args[0]!, f);
Are there any conventional TypeScript methods to achieve this setting and retrieving behavior?