当Typescript检查经典JS类时,如何解决“'this'隐式具有类型'any'”

Stu*_*t K 3 javascript typescript

我有一些使用经典JS类的旧代码,我想对它们进行类型检查。例如:

/**
 * @constructor
 */
function Test() {
    this.x = 1;
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行tsc --noImplicitThis --noEmit --allowJs --checkJs test.js输入check时,出现以下错误:

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

5     this.x = 1;
      ~~~~
Run Code Online (Sandbox Code Playgroud)

我无法通过查看https://github.com/Microsoft/TypeScript/wiki/JsDoc-support-in-JavaScript或只是猜测来找到任何类型注释来解决此错误。有办法吗?

Aar*_*all 5

这就是noImplicitThis产生该错误的原因。您需要使用一个this参数来指定this期望的类型。

使用JSDoc时,可以使用@this注释

/**
 * @constructor
 * @this Test
 */
function Test() {
    this.x = 1;
}
Run Code Online (Sandbox Code Playgroud)

在Typescript中,它写为function Test(this: Point) { ... }