TypeScript Version: 2.0.3
Code
interface UIElement {
addClickListener(onclick: (this: UIElement, e: Event) => void): void;
prop: number;
}
let uiElement: UIElement;
uiElement.addClickListener(() => {
var k = this.prop;
});
Expected behavior:
No error
Actual behavior:
tsc.exe --noImplicitThis blah.ts
blah.ts(8,10): error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.
In your example you are using an arrow function - so the this
available inside of this function is the same as the this
outside - which has no type information (any)
Use function
and you get your typed this:
interface UIElement {
addClickListener(onclick: (this: UIElement, e: Event) => void): void;
prop: number;
}
let uiElement: UIElement;
uiElement.addClickListener(function() {
var k = this.prop;
});
The behavior looks good to me. It does catch errors related to misuse of arrow functions.
Most helpful comment
In your example you are using an arrow function - so the
this
available inside of this function is the same as thethis
outside - which has no type information (any)Use
function
and you get your typed this:The behavior looks good to me. It does catch errors related to misuse of arrow functions.