首页 > 解决方案 > Typescript检查经典JS类时如何解决“'this'隐含类型'any'”

问题描述

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

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

但是,当我运行tsc --noImplicitThis --noEmit --allowJs --checkJs test.js输入检查它时,我收到以下错误:

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

5     this.x = 1;
      ~~~~

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

标签: javascripttypescript

解决方案


noImplicitThis会产生该错误。您需要使用this参数来指定this预期的类型。

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

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

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


推荐阅读