I found this function:
function sliceIntoChunks(arr, chunkSize) {
const res = [];
for (let i = 0; i < arr.length; i = chunkSize) {
const chunk = arr.slice(i, i chunkSize);
res.push(chunk);
}
return res;
}
and I want to type it:
export const sliceIntoChunks = <T>(
arr: Array<T>,
chunkSize: number
): Array<T> => {
const res: T[] = [];
for (let i = 0; i < arr.length; i = chunkSize) {
const chunk = arr.slice(i, i chunkSize);
res.push(chunk);
}
return res;
};
Getting an error here: res.push(chunk);
error:
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[]'.
How do I implement this correctly?
CodePudding user response:
The resulting array will be array of arrays, so:
const sliceIntoChunks = <T>(
arr: Array<T>,
chunkSize: number
): Array<T[]> => {
const res = [];
for (let i = 0; i < arr.length; i = chunkSize) {
const chunk = arr.slice(i, i chunkSize);
res.push(chunk);
}
return res;
};
CodePudding user response:
Array.prototype.slice returns an array, a subset of arr. So If arr is of type Array<T>, then chunk is too. But res is also of type Array<T> (or the equivalent T[]), so res.push expects an argument of type T, not Array<T>.
Try changing the type of res from T[] to T[][].
