Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to solve "'this' implicitly has type 'any'" when Typescript checking classic JS class

I have some old code that uses classic JS classes that I want to type check. For example:

/**
 * @constructor
 */
function Test() {
    this.x = 1;
}

However when I run tsc --noImplicitThis --noEmit --allowJs --checkJs test.js to type check it, I get the following error:

test.js:5:5 - error TS2683: 'this' implicitly has type 'any' because it does not have a type annotation.

5     this.x = 1;
      ~~~~

I haven't been able to find any type annotation to fix this error, either by looking at https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript or just by guessing. Is there a way?

like image 930
Stuart K Avatar asked Sep 20 '18 18:09

Stuart K


1 Answers

It's noImplicitThis which produces that error. You need to use a this parameter to specify what the type of this is expected to be.

When using JSDoc you can use a @this annotation:

/**
 * @constructor
 * @this Test
 */
function Test() {
    this.x = 1;
}

In Typescript this is written as function Test(this: Point) { ... }.

like image 167
Aaron Beall Avatar answered Oct 15 '22 07:10

Aaron Beall