![](https://user-images.githubusercontent.com/7291672/220684213-15b4b286-98aa-43dc-abb1-f10a7442eb4c.png)
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' 因为它没有类型注释。
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.typescriptlang.org/play?#code/PQKhAIAEBcE8AcCm4DeBZWB5ARgKwL7gjABQAxgPYB2AztOBeALyonjvgBmFFAXFwFcqZaAEtqACgCUrDnPATOQkeKoToAC1E1+AQyqwZKNvNOVaFADaIAdJYoBzdVppSA3OGDBwgUHITp-BtsUSoAE2dtKSlpN39wfBJ8WJIQ6EQAJ05dMmQMHFxZDm4KCJ1UcF1+KgEAW2wM+Kl+ADcKUVDY-CA
https://github.com/xgqfrms/learn-typescript-by-practice/issues/29
https://github.com/microsoft/TypeScript/issues/19639#issuecomment-1440409865