1 回答

TA貢獻1946條經驗 獲得超3個贊
這里的核心問題是,您希望返回在超類上實現克隆函數,該超類返回正在復制的任何子類實例。
首先,您需要返回類型 ,這意味著該方法返回與實例相同的類型。this
其次,您希望調用與此類相同的構造函數。除非我弄錯了,否則typescript不會讓這變得容易。的類型只是 ,而不是您可能期望的類構造函數。但是,您可以以一種提供相當強大的類型安全性的方式強制使用它。someInstance.constructorFunction
class A {
constructor(public data: string) { }
deepCopy<
// This generic argument will be the type of the class object
// that this is an instance of. It must be a subclass of A.
T extends typeof A
>(): this {
// Get the constructor as the constructor of some subclass of A.
const constructor = this.constructor as T
// Create the new instance as the same type as `this`.
const newInstance = new constructor(this.data) as this
// return the copy.
return newInstance
}
}
class B extends A {}
const b1 = new B('some data here')
const b2: B = b1.deepCopy() // works
操場
泛型參數表示函數中將是某個構造函數,該構造函數是 A 的子類。我們真的不在乎哪一個。T extends typeof AT
然后,我們可以簡單地強制一些類型腳本無法推斷的強制轉換。
但是,這種類型安全性崩潰的地方是,如果子類具有不同的構造函數簽名,這可能會中斷,因為不知道如何調用它們。deepCopy
添加回答
舉報