‘this’ 在 TypeScript 中隐式具有类型 ‘any’ 错误
‘this’ implicitly has type ‘any’ error in TypeScript
“this implicitly has type any”的错误发生在我们在类之外或在无法推断this
类型的函数中使用关键字时。this
要解决该错误,请为this
关键字添加一个类型作为函数中的第一个参数。
class Employee { constructor(public name: string, public salary: number) { this.name = name; this.salary = salary; } } interface Employee { getSalary(): number; } // 👇️ add a parameter to type `this` Employee.prototype.getSalary = function (this: Employee) { return this.salary; }; const e1 = new Employee('Tom', 100); console.log(e1.getSalary());
当 TypeScript 无法确定this
关键字的类型时,就会出现“this implicitly has type any”错误,因为我们在类外部或嵌套函数中使用了它。
在类外使用时,默认this
类型为any
。
以下是错误发生方式的示例:
class Employee { first: string; last: string; constructor(first: string, last: string) { this.first = first; this.last = last; } getFullNameFunction() { return function () { // ⛔️ Error 'this' implicitly has type // 'any' because it does not have a type annotation. return this.first + ' ' + this.last; }; } }
请注意,this
嵌套函数内部
的上下文getFullNameFunction
不是Employee
实例。
要解决这种情况下的错误,我们必须将嵌套函数转换为箭头函数,因为箭头函数使用this
封闭范围的。
class Employee { first: string; last: string; constructor(first: string, last: string) { this.first = first; this.last = last; } getFullNameFunction() { return () => { console.log(this); // ✅ this is now instance of Employee return this.first + ' ' + this.last; }; } } const e1 = new Employee('John', 'Doe'); const func = e1.getFullNameFunction(); console.log(func()); // 👉️ "John Doe"
因为this
在嵌套的箭头函数中引用了一个Employee
实例,所以我们不会再得到错误了。
或者,您可以使用闭包。
class Employee { first: string; last: string; constructor(first: string, last: string) { this.first = first; this.last = last; } getFullNameFunction() { // eslint-disable-next-line @typescript-eslint/no-this-alias const self = this; // 👈️ closure of this return function () { // ✅ this is now instance of Employee return self.first + ' ' + self.last; }; } } const e1 = new Employee('John', 'Doe'); const func = e1.getFullNameFunction(); console.log(func()); // 👉️ "John Doe"
我们分配给一个在外部函数中this
命名的变量。self
现在嵌套的命名函数可以使用self
变量,它引用 的实例Employee
。
noImplicitThis
属性true
在您的文件中设置为 时,如果在没有显式类型的情况下使用tsconfig.json
,TypeScript 会抛出错误。 this
请注意,有时 TypeScriptthis
甚至可以在类之外推断出类型。
为了解决错误,我们通常必须使用this
参数并
this
显式设置类型。
如果您无法通过设置this
为特定类型来消除错误,请尝试将其类型设置为any
.
如果要在this
隐式指定any
类型
时禁用错误报告,请在文件中将noImplicitThis
属性设置为。false
tsconfig.json
{ "compilerOptions": { // ... other settings "noImplicitThis": false } }
现在,TypeScript 在this
隐式设置为具有any
.
结论
“this implicitly has type any”的错误发生在我们在类之外或在无法推断this
类型的函数中使用关键字时。this
要解决该错误,请为this
关键字添加一个类型作为函数中的第一个参数。