[我正在尝试创建与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)
我似乎无法弄清楚我在做什么错?
您可能希望cache
是一个数组数组,即
function chunk<T>(arr: T[], chunkSize: number, cache: T[][] = []): T[][] {