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