【发布时间】:2020-11-27 16:14:44
【问题描述】:
在研究泛型时:
function newArr<T>(arr: T[], itemToAdd: string): T[] {
return arr.push(itemToAdd);
}
const arr: string[] = ["item 1", "item 2", "item 3"];
const itemToAdd: string = "item 4";
newArr<string>(arr, itemToAdd);
当我将鼠标悬停在 itemToAdd 上时,我遇到了这个错误。
Argument of type 'number' is not assignable to parameter of type 'T'.
'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
以体面的类型安全性来解决这个问题的最佳方法是什么?
【问题讨论】:
-
函数参数应该是
itemToAdd: T。 -
我试过了,但我得到了错误
Type 'number' is not assignable to type 'T[]' -
那是因为 return 类型,
.push不返回数组。此外,您不需要显式提供泛型类型,因为它可以从参数中推断出来。 -
要么使用
.concat返回一个末尾附加itemToAdd的新 数组,要么使用arr.push(itemToAdd); return arr;。.push方法总是返回数组的新长度,所以你不能使用它的返回值作为T[]。 -
我已经尝试了其中一些建议,但没有奏效。我将编辑问题以包括这些。谢谢
标签: typescript typescript-typings typescript-generics