how to fix TypeScript error 'this' implicitly has type 'any' All In One
how to fix TypeScript error 'this' implicitly has type 'any' All In One
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
'this' 隐式具有类型 'any' 因为它没有类型注释。
errors ❌
const nums = [1, 2, 3];
nums.myForEach(function(a, b, c, thisObj) {
console.log(`a, b, c =`, a, b, c);
console.log(`thisObj =`, thisObj);
console.log(`this = `, this);
});
solutions
function(this:any, ...)
👍 推荐方式
✅ just add
this: any
as the ES5 function's first argument.
只需要把 this:any
添加到函数的第一个参数位置即可,这不会影响后面正常参数的传入顺序!
const nums = [1, 2, 3];
nums.myForEach(function(this: any, a, b, c, thisObj) {
// A 'this' parameter must be the first parameter.ts(2680) ✅
console.log(`a, b, c =`, a, b, c);
console.log(`thisObj =`, thisObj);
console.log(`this = `, this);
});
"noImplicitThis": false,
禁用错误提示 👎 不推荐
tsconfig.json
{
"compilerOptions": {
// "target": "ES2022",
// "target": "ES2020",
"target": "ESNext",
// "module": "NodeNext",
"module": "ESNext",
"lib": [
"ES2015",
"ES2016",
"ES2017",
"ES2018",
"ES2019",
"ES2020",
// "ES2021",
// "ES2022",
"ESNext",
"dom",
"dom.iterable"
],
"downlevelIteration": false,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"sourceMap": true,
"sourceRoot": "./src",
"allowJs": true,
// Generate d.ts files ✅
"declaration": true,
"checkJs": false,
"noImplicitAny": false,
"baseUrl": "./src",
"locale": "zh-CN",
"noImplicitReturns": true,
// fix: https://github.com/xgqfrms/learn-typescript-by-practice/issues/29
"noImplicitThis": false,
// https://github.com/xgqfrms/vscode/issues/67
// "allowImportingTsExtensions": true,
// error TS5023: Unknown compiler option 'allowImportingTsExtensions'. ❌
// "noEmit": true,
// Option 'allowImportingTsExtensions' can only be used when either 'noEmit' or 'emitDeclarationOnly' is set.ts
"incremental": false
},
"type": "module",
"include": [
// include folder ✅
"src/**/*",
// "js-solutions/**/*",
"test/**/*"
],
"exclude": [
"node_modules",
"build",
"js-solutions/**/*",
"data-structures/**/*",
"000-xyz/**/*",
"test/**/*.spec.ts"
]
}
demos
fix: TypeScript & ES5 function this
error, 'this' implicitly has type 'any'
test ✅
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://github.com/xgqfrms/learn-typescript-by-practice/issues/29
https://github.com/microsoft/TypeScript/issues/19639#issuecomment-1440409865
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17146574.html
未经授权禁止转载,违者必究!