类型“ T”的参数不能分配给类型“ number”的参数

时间:2019-03-05 20:46:37

标签: javascript typescript lodash typescript-generics

我不知道<T>是否是数字,为什么不能将其分配给数字类型的参数?如果我将 n 的类型更改为numberany(显然),它将仍然有效。

错误:

enter image description here

代码:

const dropFoo = <T>(arr: T[], n: T): T[] => {
  return _.drop(arr, n)
};
const drop = dropFoo<number>([1, 2, 3], 1);
console.log(drop);

1 个答案:

答案 0 :(得分:1)

因为T可以是任何数字,而不仅仅是数字。 drop希望其第二个参数始终是数字。您只需将其限制为仅使用<T extends number>的数字,然后泛型根本就没有用(通常不在此处)。