Automated Overload Generation

Topics: General
May 11, 2013 at 8:59 PM
Method Overloading is available in TypeScript, I know. But it would be very useful to have the logic done by the compiler.

For example if I have the following:
class ArgumentMismatchException {}

class OverloadExample {
    public DoSomething(); // (1)
    public DoSomething(param1: string, param2: string); // (2)
    
    public DoSomething(p1?: any, p2?: any) {
        if (!p1 && !p2)
            alert('No Parameters -> (1)');
        else if (typeof p1 == 'string' && typeof p2 == 'string')
            alert('Two Parameters -> (2)');
        else
            throw new ArgumentMismatchException();
    }
}

var oe = new OverloadExample();
oe.DoSomething();
oe.DoSomething('hello', 'world');
oe.DoSomething(234);
it would be very nice if I could also write this instead:
class OverloadExample {
    public DoSomething() {
        alert('No Parameters -> (1)');
    } // (1)
    
    public DoSomething(param1: string, param2: string) {
        alert('Two Parameters -> (2)');
    } // (2)
}

var oe = new OverloadExample();
oe.DoSomething();
oe.DoSomething('hello', 'world');
oe.DoSomething(234);
and the code two route to the requested overloaded method would be automatically generated by the compiler.
May 12, 2013 at 12:04 AM
From my non-extensive knowledge of language and compiler design (OK, from reading Eric Lippert's blog) the problem here is that in the example case you've given, the resolution is simple, but in the complete set of all possible cases, the resolution can range from trivial to extremely complicated to "impossible in a dynamic language".

For example, if I am working in a typed language that supports overloaded methods, I should be able to do this:
class Resetter {
  public reset(HtmlElement element) {
    while (element.children.length > 0) {
      element.removeChild(element.children[0]);
    }
  }

  public reset(HTMLCanvasElement element {
    element.getContext("2d").clearRect(0, 0, element.width, element.height);
  }
}
That's a very simple, realistic use case, and there is no simple, object-model- or API-independent way that TypeScript can know how to resolve that overload in the JavaScript it produces.
Coordinator
May 13, 2013 at 4:17 PM
As markrendle says, there are a few issues, which have come up before (e.g. https://typescript.codeplex.com/discussions/397788).

In general, we try to keep the amount of code-rewriting to a minimum, and focus on the kind of code you would normally write in JavaScript. In this case, we'd need to rewrite the function to be called through another function (introducing new names into the output) and reflect on the types of the values given (not possible in all cases). By sticking to only overloading on the function prototype, we can stay closer to the JavaScript, and enable describing "overloading" as its done in JavaScript.