Generics and someFunction.bind(newCtx)

Topics: Language Specification
Mar 24, 2013 at 9:23 AM
Just checked the specifications of the new generics implementation and I couldn't see a way to deal with some of the more dynamic aspects of JS.

As a use-case I like to refer to the "bind" method on the Function interface. In JS the returned function of this method has of course the same type as the caller function.

Will it be possible to declare the bind method in such way that the type system is aware of this??

I couldn't see how this would be achieved in the current implementation (but perhaps I'm missing something. Of course you could always cast the result as a work around, but it would be great if there would be a more elegant solution.
Mar 24, 2013 at 9:11 PM
Edited Mar 24, 2013 at 9:16 PM
Result generics shouldn't be too much a problem IMO. Like so:
declare class Function<T> {
    (...args: any[]): T;
    bind(thisArg: any, ...args: any[]): Function<T>;
though lib.d.ts defines Function as an interface. Specifically for the bind use case, the TypeScript compiler will need to infer that T for all functions internally. I would imagine even this might work for general-purpose proxying:
declare function proxy<T>(funcToProxy: { (...args: any[]) => T }): { (...args: any[]) => T };
or even better:
declare function proxy<T extends Function>(funcToProxy: T): T;