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

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

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

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