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

时间:2017-11-27 12:47:58

标签: typescript

我想拥有2个不同的构造函数。一个用于ID,一个用于Id,firstname和boolean值。

界面: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

}

打字稿信息很明确:"期待1个参数但得到3" 我认为当我声明3个参数时,它应该自动使用第二个构造函数。

1 个答案:

答案 0 :(得分:5)

根据spec,实施的签名不包含在公共类型中。您可以编写以下内容以同时签名:

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)