簡體   English   中英

'this' 類型在 Typescript class 原型方法中推斷為 'any'

[英]'this' type inferred as 'any' in Typescript class prototype method

假設我有一個帶有_type屬性和getType方法的 class:

class Thing {
  _type: number;

  getType: () => number;
}

然后我想在 class 之外定義getType方法:

Thing.prototype.getType = function getType() {
  return this._type;
}

getType定義中,被推斷為any ,而不是Thing的類型。 但是,如果getType在 class 定義中定義,它就可以正常工作。

這有什么問題? 是否需要使用一些語法將其綁定function 定義?

在 class 中聲明的方法將this類型作為 class 的實例(盡管不能保證this實際上是運行時該類型的實例)。

定義和分配給原型的函數將受益於this的任何推斷,因為方法簽名實際上並不保留this的類型。

class Thing {
    getType() { }
}

let fn = Thing.prototype.getType // fn has type ()=> void instead of (this: Thing) => 

有一個討論來更好地鍵入this ,但它對性能的影響令人望而卻步(如果我沒記錯的話,對 class 重代碼的性能影響為 10-20%)所以它被廢棄了。 盡管上面的示例看起來微不足道,但在考慮派生類時鍵入this並不容易,因為this本質上必須是一個類型參數,這會導致速度變慢。

您可以this使用顯式注釋(額外的參數將在編譯期間被刪除):

Thing.prototype.getType = function getType(this: Thing) {
  return this._type;
}

游樂場鏈接

或者,如果在您的情況下,該方法實際上被聲明為 class 上的字段,您可以在字段簽名上為此添加注釋,並在分配它時從注釋中受益:

class Thing {
  _type!: number;
  getType!: (this: Thing) => number;
}


Thing.prototype.getType = function getType() {
  return this._type;
}

游樂場鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM