简体   繁体   中英

Type 'T' is not assignable to type 'number'

I have optional type arg func RECT(T<Date | number>), now I am checking if I get instanceOf date as arg, i am converting it to number, else i am using number directly. I am getting error Type 'T' is not assignable to type '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 {
      this.opportunityArea.dx = x1; //**TS2322: Type 'T' is not assignable to type 'number'.**
    }
}

It doesn't work because T is too generic to fit into just Date or number . If you use a type alias instead of generics then it should work.

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;
    }
}

I use else if(typeof x1 === 'number') and its working

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM