Specify type of "this" in function signature (for non-methods)

Topics: General, Language Specification
Sep 24, 2013 at 5:30 PM
Edited Sep 24, 2013 at 5:35 PM
In many JavaScript libraries (jQuery for example) a callback can be passed into the library, and when it's invoked the library will bind this to some object. For example, when firing a "click" event, jQuery binds this to the DOM element that was clicked.

Has the TypeScript team considered ways of specifying type information for this in such cases?

My idea is to allow this to appear as an argument in the function's signature. When present, TypeScript will use the type annotation to provide stronger typing. It will not consider it as an extra argument.

Continuing the jQuery example:
$("div").on("click", function(this: Element) {
    var numChildren = this.children.length; // numChildren is automatically typed as a number
    console.log("This <div> has " + numChildren + " children.");
    this.foobar(); // <-- TypeScript's compiler can catch this as a type error
The anonymous function is considered to have 0 arguments and the value of this is of type Element. Normally, this type information would be specified in a library's .d.ts file so that consumers of the API don't need to include it in their function signature.
// Original excerpt from jquery.d.ts
on(events: string, selector?: any, handler?: (eventObject: JQueryEventObject) => any): JQuery;
// Excerpt modified to include type information for this
on(events: string, selector?: any, handler?: (this: Element, eventObject: JQueryEventObject) => any): JQuery;
Has this been considered? Is it a bad idea?
Sep 24, 2013 at 6:50 PM
I think this issue https://typescript.codeplex.com/workitem/507 captures the things you're requesting. Feel free to upvote it further, definitely a reasonable thing to want.
Sep 24, 2013 at 7:04 PM
Oh wow, yeah that looks like it's exactly the same thing. Thanks!