Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

145
Views
How to solve 'T' could be instantiated with an arbitrary type which could be unrelated to 'T[]'?

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?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

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;
};

Playground

about 4 years ago · Santiago Gelvez Report

0

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[][].

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!