Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda