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

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

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