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 01 Answer
Reset to default 5The 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
版权声明:本文标题:javascript - Why Type 'number' is not assignable to type 'T'? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745642718a2667955.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论