typescript 打字稿类:“重载签名与函数实现不兼容”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39407311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:50:07  来源:igfitidea点击:

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

classangulartypescriptconstructorconstructor-overloading

提问by smartmouse

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?

但我仍然得到同样的错误。我的代码有什么问题?

回答by Nitzan Tomer

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.

两者是等价的。