我的代码如下:
$(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 - 在带有 jQuery 的 TypeScript 中,为什么我会收到错误 'this' 隐式具有类型 any,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51718539/