Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

138
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda