构造函数重载,使用可选参数,类型不兼容
来源: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
详细答案在截图里212021-08-12
相似问题