类型“ T”不可分配给类型“数字”

时间:2020-07-07 22:38:49

标签: javascript angular typescript generics

我有可选的arg func RECT(T )类型,现在我正在检查是否将instanceOf date作为arg转换为数字,否则我将直接使用number。我收到错误类型'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'.**
    }
}

2 个答案:

答案 0 :(得分:3)

它不起作用,因为T太笼统而不能只适合Datenumber。如果您使用类型别名而不是泛型,那么它应该可以工作。

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'.**
    }
}