亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用繼承的方法在深度克隆對象時保持精確鍵入

使用繼承的方法在深度克隆對象時保持精確鍵入

RISEBY 2022-08-27 09:34:00
我的結構如下:export class InteriorElement {  private x: number;  public draw(canvas: CanvasRenderingContext2D): void {    throw Error('Draw Method not implemented yet');  }}export class Seat extends InteriorElement {  public draw(canvas: CanvasRenderingContext2D): void {   canvas.drawRect(this.x, 0, 20, 20);  }}我可以使用以下命令生成一個新對象:const seat: Seat = new Seat();seat.x = 5;能用座位的抽獎方法seat.draw(this.canvasContext);現在,為了避免一遍又一遍地修改同一個座位,我想深入復制這個元素。但是,與其將方法復制/粘貼給每個孩子,我寧愿只使用IntersideElement類。因此,我希望有一個功能(我們非常邀請您改進該函數),如下所示:public deepCopy(): InteriorElement {  const deepCopy: InteriorElement = new InteriorElement(this.id);  Object.keys(this).forEach((key: string) => {    if (typeof (this[key]) === 'object') {      return this.deepCopyObject(this[key]);    } else {      deepCopy[key] = this[key];    }  });  return deepCopy;}private deepCopyObject(any: any): object {  const deepCopy: object = new Object();  Object.keys(any).forEach((key: string) => {    if (typeof (any[key]) === 'object') {      return this.deepCopyObject(any[key]);    } else {      deepCopy[key] = any[key];    }  });  return deepCopy;}我現在可以使用一個簡單的:seat.deepCopy();然而,問題在于這顯然會返回一個InsideElement。所以這樣做:const seat2: Seat = seat.deepCopy();seat2.draw(); 將導致“繪制方法尚未實現”錯誤。即使const是鍵入的,它也會收到一個InsideElement,所以從現在開始它將是一個。有沒有辦法為deepCopy提供泛型類型?像這樣:const seat2: Seat = seat.deepCopy<Seat>();這將導致:public deepCopy<T>(): T {  const object: T = new T();  [...]}不幸的是,它拋出了:“T”僅指一種類型,但在這里被用作值 - 錯誤。我如何知道InsideElement.deepCopy()副本請求哪個子項?
查看完整描述

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


查看完整回答
反對 回復 2022-08-27
  • 1 回答
  • 0 關注
  • 116 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號