Typescript: This typing not honored

Created on 9 Dec 2016  ·  1Comment  ·  Source: microsoft/TypeScript

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.

Question

Most helpful comment

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.

>All comments

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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

fwanicka picture fwanicka  ·  3Comments

CyrusNajmabadi picture CyrusNajmabadi  ·  3Comments

weswigham picture weswigham  ·  3Comments

jbondc picture jbondc  ·  3Comments

siddjain picture siddjain  ·  3Comments