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

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

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 Denunciar

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