jquery - 在带有 jQ​​uery 的 TypeScript 中,为什么我会收到错误 'this' 隐式具有类型 any

标签 jquery typescript

我的代码如下:

$(function() {

    $("table").on("click", function() {
      const button = $(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/**/*"
    ]
}

编辑2:

我的 package.json 中有以下内容

"@types/jquery": "^2.0.41",

最佳答案

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

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

4         const button = $(this);
                           ~~~~

这是因为您在 tsconfig.json 中设置了 strict: true,这也会打开 noImplicitThis。 TypeScript 的 docs声明 noImplicitThis 的意思是:

Raise error on this expressions with an implied any type.

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

修复方法是指定 this 的类型:

$(function() {

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

});

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

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

关于jquery - 在带有 jQ​​uery 的 TypeScript 中,为什么我会收到错误 'this' 隐式具有类型 any,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718539/

相关文章:

javascript - Cytoscape 布局 - 找不到这样的布局可乐

javascript - 带有鸭子类型对象的 typescript 字符串文字

jquery - 悬停后是否可以在不启动悬停本身的情况下获取 div 的属性?

javascript - 动态添加的文本区域不起作用

jquery - 使用 JQuery 处理动态字段时 Grails 表单提交失败

typescript - 将自定义指令绑定(bind)到 Angular2 中的 Observable

javascript - 如何触发 URL 与链接匹配的点击事件

javascript - DataTables 尝试使用 RequireJS 访问 datatables.net.js

typescript - 使用 CloudFormationCreateReplaceChangeSetAction 处理 yaml 文件时,如何从配置文件添加信息?

visual-studio - Visual Studio Typescript Intellisense 不遵守 tsconfig.json baseUrl