Overloading on boolean constants

Topics: Language Specification
Apr 23, 2013 at 3:13 AM
I've been playing around with the 0.9.0 alpha release and so far I love the idea of overloading on string constants to provide more specific type information. This makes perfect sense for the way the native DOM APIs behave. However, while working on a .d.ts file for the JavaScript Info Vis Toolkit (http://philogb.github.io/jit/), I ran into an interesting use-case. There were a couple of functions in the library that would return different types based off of boolean flags.

Here's an example:
    toComplex: function(simple) {
        var x = Math.cos(this.theta) * this.rho;
        var y = Math.sin(this.theta) * this.rho;
        if(simple) return { 'x': x, 'y': y};
        return new Complex(x, y);
    },
Ideally, the definition for this function would look like so:
    toComplex(simple?: boolean): Complex;
    toComplex(simple?: true): { x: number; y: number; };
Sounds like it would be even simpler to implement than string constant overloads. Also, does it make sense to also allow this functionality for numbers as well? I personally haven't seen a use-case for it, but it seems reasonable that a function may return different types based on different numeric constants (i.e. values in an enum mapped to classes).
Coordinator
Apr 23, 2013 at 1:58 PM
Indeed, overloading on other types of constants could be helpful. Strings were the first choice, because of how often they come up as part of the API in JavaScript, though in the future we might look into doing others. You should always feel free to hack to the compiler to add things like that, though, if you need them before they're officially added.