class - typescript 类 : "Overload signature is not compatible with function implementation"

标签 class angular typescript constructor constructor-overloading

我创建了以下类:

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

我收到以下错误:

Overload signature is not compatible with function implementation

我尝试了几种重载构造函数的方法,我尝试的最后一种方法是我在上面发布的方法(我从 here 获得)。

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

最佳答案

你得到那个编译错误是因为实现函数的签名不满足你声明的空构造函数。
因为你想有默认的构造函数,它应该是:

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 )

请注意,实际实现中的所有参数都是可选的,这是因为默认构造函数没有参数。
这样,实现函数就有一个满足其他两个签名的签名。

但是您可以只拥有单个签名而无需声明其他两个:

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 )

两者是等价的

关于class - typescript 类 : "Overload signature is not compatible with function implementation",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39407311/

相关文章:

javascript - Angular 8 拦截器 - 如何处理状态 200 的响应

node.js - Typescript 和 Googleapis 使用的内存激增

将 immer 用于 Redux 的 reducer 时出现 typescript 错误

jQuery - 为什么通过字符串 ($ ('<div class="foo"/>')) 创建类对象比创建相同对象并执行 addClass() 方法慢?

c++ - 如何定义派生类的非成员构造函数(在类头中)

python使用内部类动态创建类

angular - teradata-covalent 数据表在滚动和页面上重新渲染数据工作缓慢 angular 2+

css - 在 Angular Material 的垂直选项卡列表中添加选项卡按钮

php - 将 __DIR__ 常量与字符串连接作为数组值,它是 PHP 中的类成员

javascript - Angular 7 错误通知不显示