overridden functions

Topics: Language Specification
Oct 2, 2012 at 8:26 PM

i know that currently only one of the functions of a given name can have a body which is great for specifying the different type signatures.

it would be pretty amazing if TypeScript would allow multiple overridden bodies and behind the scenes output a single dispatcher based on the types of its arguments.

 

something like:

class Bar
{
	inc(a:number)
	{
		return a + 1;
	}
	inc(a:string)
	{
		return parseInt(a) + 1;
	}
}

 

goes to

var Bar = (function () {
    function Bar() { }
    Bar.prototype.__inc_number = function (a) {
        return a + 1;
    };
    Bar.prototype.__inc_string = function (a) {
        return parseInt(a) + 1;
    };
    Bar.prototype.inc = function (a) {
		if (typeof a === "number")
			return this.__inc_number (a);
		if (typeof a === "string")
			return this.__inc_string (a);
		throw new Error ();
	};
    return Bar;
})();


i guess distinguishing between TypeScript types at runtime then becomes an issue...

Oct 2, 2012 at 9:48 PM

You mean overloaded, not overridden. As you point out yourself, this wouldn't work with the type system anyway, as interfaces can be a purely compile-time concept. This greatly limits the utility of something like this.

Oct 3, 2012 at 3:44 AM
Edited Oct 3, 2012 at 3:45 AM

yeah, but i think that the problem of being able to distinguish types at runtime needs to be addressed anyway, if for nothing more than the ability to hand-write polymorphic methods using those types.

class Bar {
	inc(a:Foo);
	inc(a:Goo);
	inc(a:any) {
		// what goes here now?
	}
}

once that's solved...