Re:Plottable.js – Flexible, interactive charts for the web
by talldan on Monday September 05, 2016 @12:40PM
(#12431150)
It feels complicated due to not using separate getter and setter functions. By splitting it into two functions the annotations could be reduced as well. I wonder what the reason for not taking that approach was.
Re:Plottable.js – Flexible, interactive charts for the web
by chrismorgan on Monday September 05, 2016 @04:21PM
(#12432042)
It’s common in JavaScript to have method overloading for getters and setters like this. jQuery is probably the best-known example; .css('property') is a getter and .css('property', value) a setter.
x.connectorsEnabled(boolean) on line 31 is a setter, return `this` for the benefit of method chaining.
That then leaves the actual definition which goes through to the JavaScript: it has an optional argument to satisfy both plausible signatures and starts on line 32.
In short, the first two are basically hints for TypeScript (if the signature is such-and-such, its return type is actually more restricted than `any`), while the third has the actual implementation.
For something similar consider how the type of callback in `addEventListener(type, callback)` depends on `type`: it’s always going to be a function taking an Event, but for e.g. type 'mousedown' it’s actually more than that, it’s a MouseEvent. So the TypeScript definitions in dom.d.ts or whatever it is (I haven’t had opportunity to actively use TypeScript for a while) has a whole lot of definitions: `addEventListener('mousedown', (event: MouseEvent) => void)`, `addEventListener('focus', (event: FocusEvent) => void)`, &c. (And because it’s just definitions, not the implementation, there is no actual implementation of `addEventListener(string, (event: Event) => void)`. This connectorsEnabled case does have the actual implementation.) In type system terms, think of it as a very restricted form of dependent typing.