‘this’ 在 TypeScript 中隐含类型为 ‘any’ 错误

‘this’ 在 TypeScript 中隐式具有类型 ‘any’ 错误

‘this’ implicitly has type ‘any’ error in TypeScript

“this implicitly has type any”的错误发生在我们在类之外或在无法推断this类型的函数中使用关键字时。this要解决该错误,请为this关键字添加一个类型作为函数中的第一个参数。

索引.ts
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

以下是错误发生方式的示例:

索引.ts
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封闭范围的。

索引.ts
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实例,所以我们不会再得到错误了。

或者,您可以使用闭包。

索引.ts
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
属性设置为
falsetsconfig.json

tsconfig.json文件
{ "compilerOptions": { // ... other settings "noImplicitThis": false } }

现在,TypeScript 在this隐式设置为具有any.

结论

“this implicitly has type any”的错误发生在我们在类之外或在无法推断this类型的函数中使用关键字时。this要解决该错误,请为this关键字添加一个类型作为函数中的第一个参数。