在带有 jQ​​uery 的 TypeScript 中,为什么我会收到错误“this”隐式具有任何类型

Mar*_*ary 1 jquery typescript

我的代码如下:

$(function() {

    $("table").on("click", function() {
      const button = $(this);
    });

});
Run Code Online (Sandbox Code Playgroud)

我的错误是:

this 隐式具有“any”类型,因为它没有类型注释。

我该如何修复这个错误?

编辑:

我的 tsconfig.json 如下:

{
    "compilerOptions": {
        "module": "commonjs",
        "target": "es6",
        "noImplicitAny": true,
        "moduleResolution": "node",
        "sourceMap": true,
        "strict": true,
        "outDir": "dist",
        "baseUrl": ".",
        "paths": {
            "*": [
                "node_modules/*",
                "src/types/*"
            ]
        }
    },
    "include": [
        "src/**/*"
    ]
}
Run Code Online (Sandbox Code Playgroud)

编辑2:

我的 package.json 中有以下内容

"@types/jquery": "^2.0.41",
Run Code Online (Sandbox Code Playgroud)

ros*_*dia 5

问题几乎正是编译器所说的:

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

4         const button = $(this);
                           ~~~~
Run Code Online (Sandbox Code Playgroud)

那是因为您已经strict: true设置了tsconfig.json,它也会打开noImplicitThis。TypeScript 的文档指出这noImplicitThis意味着:

使用隐含类型对此表达式引发错误any

由于您在事件处理程序中使用它之前没有指定类型this,因此您会收到错误。

修复方法是指定以下类型this

$(function() {

    $("table").on("click", function(this: HTMLButtonElement) {
      const button = $(this);
    });

});
Run Code Online (Sandbox Code Playgroud)

这将告诉 TypeScript 您的事件处理程序中的预期类型是什么this

或者,您可以在您的 中更改strict为,但这可能不是一个可行的选择。falsetsconfig.json

  • 对于任何其他对将 `this` 指定为函数参数感到困惑的人,请在此处的 TS 文档中进行解释:https://www.typescriptlang.org/docs/handbook/functions.html#this-parameters (2认同)