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

115
Vistas
How to compare 2 inherited classes in Typescript

Consider we have 2 classes Animal and Dog. Here Dog class is inherited from Animal class.

I need to check the type of this objects

how can I achieve this


class Animal {}
class Dog extends Animal {}

//This obj can have both classes
const mixedObj: Animal | Dog = new Dog();

//---> here When i compare mixedObj with Animal class i need to get `false` but `true` is returned
console.log(mixedObj instanceof Animal);// returns: `true` 

console.log(mixedObj instanceof Dog);// returns: true

has any other ways to solve this problem...?

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

0

Fundamentally, you're is asking about the runtime value of mixedObj, which is a JavaScript thing rather than a TypeScript thing.

instanceof Animal will be true for any object that has Animal.prototype anywhere in its prototype chain (typically because it was created by the Animal constructor, directly or indirectly [for instance, via Dog]). If you want to see if mixedObj contains a Dog, specifically, and not an Animal, you need to look at the constructor property:

class Animal {}
class Dog extends Animal {}

//This obj can have either class
const mixedObj/*: Animal | Dog*/ = new Dog();

console.log(mixedObj.constructor === Animal);// returns: `false` 

console.log(mixedObj.constructor === Dog);// returns: `true`

Playground link

But, that's generally an antipattern. A better way, particularly since it'll work with TypeScript at compile-time, is to give Dog some feature that Animal doesn't have and test for that feature:

class Animal {
}

class Dog extends Animal {
    bark() {
        console.log("Woof!");
    }
}

//This obj can have either class
const mixedObj/*: Animal | Dog*/ = new Dog();

console.log("bark" in mixedObj); // returns: `true` (would be `false` for an `Animal`)

if ("bark" in mixedObj) {
    mixedObj.bark(); // No error, because TypeScript knows that it's a `Dog`
}

Playground link

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