Home > Enterprise >  How to compare 2 inherited classes in Typescript
How to compare 2 inherited classes in Typescript

Time:04-29

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

CodePudding user response:

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

  • Related