我想要 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/