Specify the type for "this" in function type

Topics: Language Specification
Mar 25, 2014 at 12:52 PM
The spec says in section 4.2
  • In a function declaration or a standard function expression, this is of type Any.
My question is why this was chosen, as opposed to allowing a function to specify the expected type of this along with specifying the type of its parameters.

For example, in doing:
inputBox.onmouseenter = function (ev:MouseEvent) {
    this.style.backgroundColor = '#ddd';
The usage of the style property is not subject to type checking, because the type for HTMLElement.onmouseenter is only:
    onmouseenter: (ev: MouseEvent) => any;
where something like
    onmouseenter: HTMLElement.(ev: MouseEvent) => any;
would enable the usage of this to be checked along with the parameters and return type, and would match a function literal such as:
inputBox.onmouseenter = function HTMLElement.(ev:MouseEvent) {
    this.style.backgroundColor = '#ddd';
Doesn't the reasoning for type checking of parameters also apply to this, since when a method is called, this is nothing more than an implied parameter?

Mar 25, 2014 at 5:23 PM
This will probably be changed in a future version, based on past comments by the TS team. You can vote on the issue here: https://typescript.codeplex.com/workitem/507.
Mar 26, 2014 at 1:23 AM
I've voted for the issue. Thanks