简体   繁体   中英

How can I do constructor overloading in a implemented interface in 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.

Classes

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

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.

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

You can also read the TypeScript FAQ entry on this

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM