Support optional ambient "this" pointer typing in callback/function signatures

Topics: General, Language Specification
Nov 27, 2012 at 8:46 PM

Currently typescript will type the "this" pointer in function callbacks as "any." Arrow syntax lets us capture "this" from the outer scope, and this can enable proper typing. It would be nice to be able to provide an optional "ambient this" declaration in function signatures:

(declare this : MyType, first: number, second: string) : any;

The rules would be:

1) the declaration is obviously optional
2) if specified, should be first parameter
3) cannot be used with arrow syntax lambdas (should be compiler error)
 
I know you can cast as needed to get the intellisense but I'd rather not put this responsibility on the implementer of the function. Ideally it should be part of the definition.

Example with Sammy:

var app = $.sammy("#view", function() {
     // define default route
     this.get("#/", function() { ... } 
});

In the above case, typescript can only type this as any.

Thoughts?

Coordinator
Nov 28, 2012 at 11:54 PM

@oisin: We've actually had discussions about a feature exactly like what you describe, and I believe it is a natural extension of current TypeScript which would enable use cases like the example you mention.  Because 'this' is a keyword, we have actually talked about it as being written like:

var f: (this: MyType, first: number) => any;

And similarly, for implementations:

function f(this: MyType, first: number) { return 3; }

There's several unanswered questions around the precise rules for how this is treated in assignment compatibility, whether methods on classes have 'this' types, etc. 

 

Coordinator
Nov 28, 2012 at 11:56 PM
This discussion has been copied to a work item. Click here to go to the work item and continue the discussion.