串联通用打字稿数组时出错

问题描述 投票:0回答:1

[我正在尝试创建与lodash提供的功能类似的自定义“分块”功能,但一直遇到泛型和数组问题。

这是功能代码:

function chunk<T>(arr: T[], chunkSize: number, cache: T[] = []): T[] {
    const tmp = [...arr];
    if (chunkSize <= 0) return cache;
    while (tmp.length) cache.push(tmp.splice(0, chunkSize));
    return cache;
}

尝试将接头压入cache阵列时发生编译错误:

Argument of type 'T[]' is not assignable to parameter of type 'T'.
  'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'.ts(2345)

我似乎无法弄清楚我在做什么错?

typescript typescript-generics
1个回答
0
投票

您可能希望cache是一个数组数组,即

function chunk<T>(arr: T[], chunkSize: number, cache: T[][] = []): T[][] {
© www.soinside.com 2019 - 2024. All rights reserved.