最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Why Type 'number' is not assignable to type 'T'? - Stack Overflow

matteradmin5PV0评论
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.

Post a comment

comment list (0)

  1. No comments so far