smartmouse smartmouse - 3 months ago 20
TypeScript Question

Typescript class: "Overload signature is not compatible with function implementation"

i created the following class:

export class MyItem {
public name: string;
public surname: string;
public category: string;
public address: string;

constructor();
constructor(name:string, surname: string, category: string, address?: string);
constructor(name:string, surname: string, category: string, address?: string) {
this.name = name;
this.surname = surname;
this.category = category;
this.address = address;
}
}


I get the following error:
Overload signature is not compatible with function implementation

I tried several ways to overload the constructor, the last one i tried is that i posted above (that i get from here)

But i still get the same error. What's wrong with my code?

Answer

You get that compilation error because the signature of the implementation function does not satisfy the empty constructor you declared.
As you want to have the default constructor, it should be:

class MyItem {
    public name: string;
    public surname: string;
    public category: string;
    public address: string;

    constructor();
    constructor(name:string, surname: string, category: string, address?: string);
    constructor(name?: string, surname?: string, category?: string, address?: string) {
        this.name = name;
        this.surname = surname;
        this.category = category;
        this.address = address;
    }
}

(code in playground)

Notice that all of the arguments in the actual implementation are optional and that's because the default constructor has no arguments.
This way the implementing function has a signature that satisfies both other signatures.

But you can then just have that single signature with no need to declare the other two:

class MyItem {
    public name: string;
    public surname: string;
    public category: string;
    public address: string;

    constructor(name?: string, surname?: string, category?: string, address?: string) {
        this.name = name;
        this.surname = surname;
        this.category = category;
        this.address = address;
    }
}

(code in playground)

The two are equivalent.