我的代码如下:
$(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)
问题几乎正是编译器所说的:
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
| 归档时间: |
|
| 查看次数: |
4659 次 |
| 最近记录: |