有没有人在 TypeScript 中完成构造函数重载。在语言规范(v 0.8)的第 64 页,有描述构造函数重载的语句,但没有给出任何示例代码。
我现在正在尝试一个非常基本的类声明;它看起来像这样,
interface IBox {
x : number;
y : number;
height : number;
width : number;
}
class Box {
public x: number;
public y: number;
public height: number;
public width: number;
constructor(obj: IBox) {
this.x = obj.x;
this.y = obj.y;
this.height = obj.height;
this.width = obj.width;
}
constructor() {
this.x = 0;
this.y = 0;
this.width = 0;
this.height = 0;
}
}
当使用 tsc BoxSample.ts 运行时,它会抛出一个重复的构造函数定义——这很明显。任何帮助表示赞赏。
原文由 Ted 发布,翻译遵循 CC BY-SA 4.0 许可协议
一般来说,对于 N 个重载,最好使用:
至少现在我们可以检查走哪条路线并采取相应的行动