我有可选的arg func RECT(T
rect<T extends Date | number>(x1:T, y1:T,x2?:T, y2?:T) {
if(x1 instanceof Date) {
this.opportunityArea.dx = this.returnNumberFunc(x1);
} else {
this.opportunityArea.dx = x1; //**TS2322: Type 'T' is not assignable to type 'number'.**
}
}
答案 0 :(得分:3)
它不起作用,因为T
太笼统而不能只适合Date
或number
。如果您使用类型别名而不是泛型,那么它应该可以工作。
type DateOrNum = Date | number;
rect(x1: DateOrNum, y1: DateOrNum, x2 ?: DateOrNum, y2 ?: DateOrNum) {
if (x1 instanceof Date) {
this.opportunityArea.dx = this.returnNumberFunc(x1);
} else {
this.opportunityArea.dx = x1;
}
}
答案 1 :(得分:0)
我使用否则if(typeof x1 ==='number')及其工作原理
rect<T extends Date | number>(x1:T, y1:T,x2?:T, y2?:T) {
if(x1 instanceof Date) {
this.opportunityArea.dx = this.returnNumberFunc(x1);
} else if(typeof x1 === 'number'){
this.opportunityArea.dx = x1; //**TS2322: Type 'T' is not assignable to type 'number'.**
}
}