Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!