构造函数重载,使用可选参数,类型不兼容

来源:3-7 【构造器重载应用】图形面积的两种实现

ldcute

2021-08-12

图片描述

如上图,ts 4.3.5 ,height 使用可选参数报错,能否在不添加 undefined 的情况下处理。

type type_charParam = {
  width?: number;
  height?: number;
  radius?: number;
};

class Square {
  public width: number;
  public height: number;

  constructor(width_: number, height_: number);
  constructor(value: type_charParam);
  // constructor(paramObjOrWidth_: any, height_: number = 0) {
  constructor(paramObjOrWidth_: any, height_?: number) {
    if (typeof paramObjOrWidth_ === "object") {
      this.width = paramObjOrWidth_.width;
      this.height = paramObjOrWidth_.height;
    } else {
      this.width = paramObjOrWidth_;
      this.height = height_;
    }
  }

  public getArea(): number {
    return this.width * this.height;
  }
}

let square1 = new Square(4, 5);
console.log(`square1`, square1.getArea());

let squareObj100 = { width: 5, height: 20 };

let square2 = new Square(squareObj100);
console.log(`square2`, square2.getArea());
写回答

1回答

keviny79

2021-08-12


6115131200018e7e11310669.jpg
详细答案在截图里

2
1
keviny79
这个是针对可选参数设置,也可以给方法参数默认值
2021-08-12
共1条回复

晋级TypeScript高手,成为抢手的前端开发人才

轻松驾驭 TypeScript 高级用法, 突破前端成长瓶颈

871 学习 · 425 问题

查看课程