原文 - 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;
};