[英]'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.