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

176
Vistas
Cant push to UnionType array

I am playing around with UnionTypes in TS and I thought that I could create a valid scenario where they could be used, but I do not understand why this is breaking with the error of:

Argument of type '{ name: string; }' is not assignable to parameter of type 'string & { name: string; }'

I know ways to "force" this partical approach, but I want to understand why this does not work.

let newArray: string[] | { name: string }[] = new Array();

//just a boolean to know when is one type or the other
    if (isMultiple) {
      otherArray.forEach((item: { name: string }) => {
        newArray.push(item)
      })
    }
    else {
      otherArray.forEach((item: { name: string }) => {
        newArray.push(item.name)
      });
    }

    return newArray
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Unless you want to allow mixed arrays (let newArray: (string | { name: string })[]), you can use

// just a boolean to know when is one type or the other
if (isMultiple) {
  const newArray: { name: string }[] = [];
  otherArray.forEach((item: { name: string }) => {
    newArray.push(item)
  });
  return newArray;
} else {
  const newArray: string[] = [];
  otherArray.forEach((item: { name: string }) => {
    newArray.push(item.name)
  });
  return newArray;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You cant have both types of arrays at the same time. You could do this and define it then create it separately in the if statement

let newArray: string[] | { name: string }[];

//just a boolean to know when is one type or the other
    if (isMultiple) {
      newArray = new Array< { name : string }>();
      otherArray.forEach((item: { name: string }) => {
        newArray.push(item)
      })
    }
    else {
      newArray = new Array<string>();
      otherArrayforEach((item: { name: string }) => {
        newArray.push(item.name)
      });
    }

    return newArray
about 4 years ago · Juan Pablo Isaza 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