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);
});
solution
fix: TypeScript & ES5 function this
error, 'this' implicitly has type '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);
});
demos
test ✅