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

141
Vistas
Se bifurcan según el tipo de un objeto.

En TypeScript, ¿cómo puedo verificar el tipo de un objeto y ramificarme según ese tipo?

 const createAnimalForId(animalId: AnimalIdsEnum): CatAnimal | BirdAnimal { // animalData has type: CatAnimalData | BirdAnimalData | undefined const animalData = animalsMap.get(animalId); // Q: How can I check the type here? if(animalData "is of type" CatAnimalData) { // NB: I want it to be aware that animalData here is of type CatAnimalData return new CatAnimal(animalData); } // Q: How can I check the type here? else if(animalData "is of type" BirdAnimalData) { // NB: I want it to be aware that animalData here is of type BirdAnimalData return new BirdAnimal(animalData); } else { throw new RangeError("Animal type not recognised"); } }

NB: CatAnimal y BirdAnimal heredan de AbstractAnimal .

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

¿Cómo puedo comprobar el tipo de un objeto?

Dado que estos tipos se implementan como class es, solo puede usar la instanceof de:

 if (animalData instanceof CatAnimalData) { … } if (animalData instanceof BirdAnimalData) { … }

… y ramificarse en función de ese tipo?

No. Este es un diseño feo, no extensible. En su lugar, haga que todas sus entradas implementen un toAnimal o getAnimal o createAnimal , y luego simplemente llame a eso:

 export class AbstractAnimalData { name: string; abstract createAnimal(): Animal { throw new RangeError("Animal type not recognised"); } } export class CatAnimalData extends AbstractAnimalData { favouriteFood: string; // NB: Leaving out the constructor for brevity createAnimal(): CatAnimal { return new CatAnimal(this); } } export class BirdAnimalData extends AbstractAnimalData { archEnemy: string; // NB: Leaving out the constructor for brevity createAnimal: BirdAnimal { return new BirdAnimal(animalData); } }

después

 function createAnimalForId(animalId: AnimalIdsEnum): Animal { const animalData = animalsMap.get(animalId); if (!animalData) { throw new RangeError(`AnimalId '${animalId}' not supported`); } return animalData.createAnimal(); // ^^^^^^^^^^^^^^^ }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puede verificar si la propiedad existe en animalType

 const createAnimalForId(animalId: AnimalIdsEnum): CatAnimal | BirdAnimal { // animalData has type: CatAnimalData | BirdAnimalData | undefined const animalData = animalsMap.get(animalId); if('favouriteFood' in animalData) { // CatAnimalData return new CatAnimal(animalData); } else if("archEnemy" in animalData) { //BirdAnimalData return new BirdAnimal(animalData); } else { throw new RangeError("Animal type not recognised"); } }
about 4 years ago · Juan Pablo Isaza Denunciar

0

Una solución que se me ocurre sería la siguiente. Sin embargo, esto tiene el problema de que, dentro de los casos condicionales, TypeScript no es consciente del tipo específico de animalData .

Según tengo entendido, esto significa que tendría que lanzarlo manualmente, lo que no creo que sea lo ideal.

 const createAnimalForId(animalId: AnimalIdsEnum): CatAnimal | BirdAnimal { // animalData has type: CatAnimalData | BirdAnimalData | undefined const animalData = animalsMap.get(animalId); if(animalData.type === animalType.catAnimal) { // Problem: TypeScript is not aware of the specific type of animalData here return new CatAnimal( animalData // as CatAnimalData ); } else if(animalData.type === animalType.birdAnimal) { // NB: I want it to be aware that animalData here is of type BirdAnimalData return new BirdAnimal( animalData // as BirdAnimalData ); } else { throw new RangeError("Animal type not recognised"); } }
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