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

358
Visualizações
How to use a variable as string or object in TypeScript?

I have a variable that can either be a string or object like this:

value?: string | { name: string, type: string }

Trying something below but I get a compile error:

console.log(value?.name || value)
console.log(value?.type)

How can use this variable if it can be either type?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

In this case you can do:

console.log(typeof value === 'string' ? value : value?.name)

Typescript can narrow the type using type-guards, see here for more details.

about 4 years ago · Juan Pablo Isaza Relatório

0

So you have two options

console.log(typeof value === 'string' ? value : value.name);

But as you used ?: in definition for this value (allowing undefined) and as i think that console is only for simple example there

if (value === undefined) {
} else if (typeof value === 'string') {
} else {
}

Would be best.

This issue you found is mostly done because both values for value variable are objects and ts saw that the types are not compatible and asks you to narrow them by hand

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