1

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.

Community
  • 1
  • 1
Fran b
  • 3,016
  • 6
  • 38
  • 65

1 Answers1

4

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

Ryan Cavanaugh
  • 209,514
  • 56
  • 272
  • 235