【问题标题】:How to type a generic function that uses Array.push()?如何键入使用 Array.push() 的泛型函​​数?
【发布时间】: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


【解决方案1】:

我通过这样做得到了答案:

function newArr<T>(arr: T[], itemToAdd: T): T[] {
  arr.push(itemToAdd);
  return arr;
}

我忘记设置 itemToAdd: T 并且没有返回数组。

【讨论】:

    猜你喜欢
    • 2021-06-15
    • 2019-08-02
    • 2019-07-19
    • 2021-11-17
    • 2022-01-25
    • 1970-01-01
    • 2020-02-27
    • 2019-06-16
    • 2020-01-20
    相关资源
    最近更新 更多