簡體   English   中英

如何在 TypeScript 中重載接口?

[英]How to overload interface in TypeScript?

我有一個界面:

export interface EditAction {
    action: (p?: Point) => any;
    undo(): void;
    redo(): void;
    complete: () => any;
    dispose: () => void;
}

然后有一個具體的 class 實現了這個接口:

export class LineAction implements EditAction {
      action(x: number, y: number) {
        alert('ok');
    }
}

export class PointAction implements EditAction {
  action(p: Point) {
    alert('ok');
}

}

所有實現中的方法action()具有不同數量的參數。

如何超載呢?

action: (p?: Point) => any;
action: (x:number, y: number) => any;

您的接口定義不太正確,一旦解決了問題,您就可以輕松定義覆蓋:

export interface EditAction {
    action(p?: Point): any;
    action(x: number, y: number): any;
    /* ... */
}

在您的 class 中,您可以通過創建與接口匹配的簽名和可以處理所有可能參數的基礎方法來實現覆蓋:

export class PointAction implements EditAction {
    action(p?: Point): any;
    action(x: number, y: number): any;
    action(xOrP: Point | number, y?: number) {
      const p = (typeof xOrP === 'number') ? { x: xOrP, y } : xOrP;
      // do stuff...
    }
    /* ... */
}

如果你實現一個接口,你必須處理所有可能的參數。 您最好創建一個通用接口:

export interface EditAction<T> {
    action: (t?: T) => any;
    undo(): void;
    redo(): void;
    complete: () => any;
    dispose: () => void;
}
export class LineAction implements EditAction<Line> {
  action(line: Line) {
     alert('ok');
  }
}
export class PointAction implements EditAction<Point> {
  action(p: Point) {
    alert('ok');
  }
}

如果我正確理解您的問題,我認為您可能想要利用 generics 和Parameters實用程序類型而不是重載。 例如:

export interface EditAction<T extends ((...args: any) => R) = ((...args: any) => any), R = any> {
  action(...params: Parameters<T>): R
  // ....
}

// Implementation:
export class LineAction implements EditAction {
  action(x: number, y: number) {
    alert('ok');
  }
}

// Optionally, be explicit
export class PointAction implements EditAction<(p: Point) => any, Point> {
  action(p: Point) {
    alert('ok');
  }
}

暫無
暫無

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

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