Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 809
smartmouse Avatar asked Sep 09 '16 08:09

smartmouse


1 Answers

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.

like image 118
Nitzan Tomer Avatar answered Sep 20 '22 12:09

Nitzan Tomer