typescript 构造函数重载,期望参数少于给定

标签 typescript

我想要 2 个不同的构造函数。一个仅用于 ID,一个用于 ID、名字和 bool 值。

接口(interface):person.ts

export interface Person {
  id: number;
  firstname?: string;
  good?: boolean;
}

类:Employee.ts

import { Person } from './person';

export class Employee implements Person {

  id: number;

  constructor(id: number);
  constructor(id: number, firstname?: string, public good?: boolean) { }
}

应用:

import { Employee } from './employee';

export class AppComponent {
  e1 = new Employee(3); // does work
  e2 = new Employee(2,'Mr Nice', true); // does not work

}

typescript 消息很清楚:“期望 1 个参数但得到 3 个” 我认为当我声明 3 个参数时,它应该自动与第二个构造函数一起工作。

最佳答案

根据 spec实现的签名不包含在公共(public)类型中。您可以编写以下内容以获得两个签名:

export class Employee implements Person {

    id: number;

    constructor(id: number);
    constructor(id: number, firstname?: string, good?: boolean);
    constructor(id: number, public firstname?: string, public good?: boolean) { }
}

同样在这种情况下,您实际上不需要两个重载。将最后两个参数声明为可选参数同样有效:

export class Employee implements Person {
    id: number;
    constructor(id: number, public firstname?: string, public good?: boolean) { }
}
new Employee(10)
new Employee(10, "", true)

关于 typescript 构造函数重载,期望参数少于给定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47511377/

相关文章:

javascript - Angular Material 2 (MatDatepickerModule) - 在日期选择器中选择的日期偏移 1 天

typescript :为什么函数参数上的不同数据类型不会引发错误?

typescript - typescript 类型中的 "three dots"是什么意思?

typescript - NestJS - 如何使用@Body() 装饰器访问帖子正文?

typescript - 使用 typescript 在 Redux thunk 中返回 promise

angular - 如何为 ng2-charts 条形图设置静态标签?

javascript - 从 typescript 访问 HTML header 中包含的 javascript 变量

javascript - 如何使用正则表达式在单词和空格之间查找?

javascript - 在 Jasmine 测试中模拟声明常量

angular - 删除整行 Angular 2 Material ?