TypeScript 中的构造函数重载

新手上路,请多包涵

有没有人在 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 许可协议

阅读 1.4k
1 个回答

一般来说,对于 N 个重载,最好使用:

 constructor(obj?: {fromType1: IType1} | {fromType2: IType2}) {
    if(obj){
      if(obj.fromType1){
        //must be of form IType1
      } else if(obj.fromType2){
        //must have used a IType2
      } else {
        throw "Invalid argument 1"
      }
    } else {
      //obj not given
    }
}

至少现在我们可以检查走哪条路线并采取相应的行动

原文由 Sancarn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进