【问题标题】:How can I do constructor overloading in a implemented interface in TypeScript?如何在 TypeScript 中实现的接口中进行构造函数重载?
【发布时间】:2016-08-02 03:24:09
【问题描述】:

我试图重载实现接口的类的构造函数,但出现以下错误:

[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 || ""
      };
}

我发现了其他类似的问题 (Constructor overload in TypeScript),但我遗漏了一些东西,因为它不起作用。打字稿版本是 1.8.9。

【问题讨论】:

    标签: typescript typescript1.8


    【解决方案1】:

    实现签名不可见。您需要声明所有调用者应该看到的重载,然后编写实现主体。

    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 entry on this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-28
      • 2014-11-27
      • 1970-01-01
      • 2012-09-24
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多