簡體   English   中英

如何在TypeScript的已實現接口中實現構造函數重載?

[英]How can I do constructor overloading in a implemented interface in TypeScript?

我試圖重載實現接口的類的構造函數,但出現以下錯誤:

[0] app/foo.ts(12,5): error TS2394: Overload signature is not compatible with function implementation.

班級

export interface Item {
    time: number;
}

export class Foo implements Item {
    public time: number;
    public name: string;

    constructor();
    constructor(
        time: number,
        name: string
    ) { 
        this.time = id || -1
        this.name = name || ""
      };
}

我發現了其他類似的問題( TypeScript中的Constructor重載 ),但是我丟失了一些東西,因為它不起作用。 打字稿版本為1.8.9。

實現簽名不可見。 您需要聲明調用者應該看到的所有重載,然后編寫實現主體。

export interface Item {
    time: number;
}

export class Foo implements Item {
    public time: number;
    public name: string;

    constructor();
    constructor(
        time: number,
        name: string
    );
    constructor(
        time?: number,
        name?: string
    ) { 
        this.time = id || -1
        this.name = name || ""
      };
}

您也可以在此閱讀TypeScript FAQ條目。

暫無
暫無

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

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