Skip to main content

解决 TypeScript 中出现的 'this' implicitly has type 'any' error 问题

· One min read
Alan

原文 - Fix - 'this' implicitly has type 'any' error in TypeScript

在TypeScript中, 如果在class外部或者function内部使用this时, TypeScript无法推导出this类型, 导致提示以下错误:

'this' implicitly has type 'any' error

要解决这个问题需要在函数的第一个参数指定this的类型即可:

class Employee {
constructor(public name: string, public salary: number) {
this.name = name;
this.salary = salary;
}
}

interface Employee {
getSalary(): number;
}

Employee.prototype.getSalary = function (this: Employee) { // add a parameter to type `this`
return this.salary;
};