admin管理员组

文章数量:1435507

function say3<T>(a: T): T { 
    return a + 1; 
} 
let speak = say3<number>(1)

I tried the demo, but it says " Type 'number' is not assignable to type 'T'.' T isn't a number?

function say3<T>(a: T): T { 
    return a + 1; 
} 
let speak = say3<number>(1)

I tried the demo, but it says " Type 'number' is not assignable to type 'T'.' T isn't a number?

Share Improve this question edited Nov 28, 2018 at 2:50 user47589 asked Nov 28, 2018 at 2:06 SanGo MiscroSanGo Miscro 331 silver badge3 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 5

The problem here is with the operation + 1. Typescript can't determine if you're doing a number sum, a string concatenation or even a BigInt operation. In fact, because the result of a variable of type T(where T is any possible type) plus 1 is not well defined and might even return a type different from T! A paticular case that es to mind is []+1=="1" or {}+1==1, cases where T is an Array and an Object while the function would return a string or a number respectively.

When you template your functions, the function needs to be well defined regardless of possible T types. In other words, yeah T isn't a number even if you explicitly pass a number later.

A possible fix would be to explicitly determine that the return type is a number and to limit T:

function say3<T extends number>(a: T): number {
  return a + 1;
}
let speak = say3<number>(1)

Or if you really want T to work with other types, you can do operator overloading:

function say3(a: string): string 
function say3(a: number): number
function say3(a: any[]): string
function say3(a: object): number
function say3(a: null): number
function say3(a: undefined): number
function say3(a: any) { 
    return a+1; 
} 
let speak = say3(1)

Either way, you can't call an operator over a non-defined type.

本文标签: javascriptWhy Type 39number39 is not assignable to type 39T39Stack Overflow