如何在TypeScript的已实现接口中实现构造函数重载? [英] How can I do constructor overloading in a implemented interface in TypeScript?

查看:863
本文介绍了如何在TypeScript的已实现接口中实现构造函数重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to overload the constructor of a class which implements an interface but I'm getting the following error:

[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中的构造函数重载),但我缺少一些东西因为它不起作用.打字稿版本为1.8.9.

I found other similar questions (Constructor overload in TypeScript) but I'm missing something because it doesn't work. The typscript versions is 1.8.9.

推荐答案

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

The implementation signature is not visible. You need to declare all the overloads callers should see, then write the implementation body.

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

您还可以阅读 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆