Asken
Asken

Reputation: 8051

Why can't I use this inside function?

Code:

const f: any = function(...args: any[]) {
    const a = this;
};

Error:

semantic error TS2683 'this' implicitly has type 'any' because it does not have a type annotation.

Upvotes: 0

Views: 976

Answers (1)

Aleksey L.
Aleksey L.

Reputation: 37938

You have noImplicitThis compiler option enabled, and in new f function this expression implicitly has the type any - hence the error.

To fix it - just specify the type explicitly using "fake" this parameter:

const f: any = function(this: typeof target, ...args: any[]) {
    // ...
};

By default the type of this inside a function is any. Starting with TypeScript 2.0, you can provide an explicit this parameter. this parameters are fake parameters that come first in the parameter list of a function

Upvotes: 2

Related Questions