class Animal {} class Dog extends Animal {} const pet = new Dog(); console.log(pet instanceof Dog); console.log(pet instanceof Animal);
The pet is an instance of Dog, so pet instanceof Dog is true. Since Dog extends Animal, pet instanceof Animal is also true.
interface Vehicle {}
class Car implements Vehicle {}
const myCar = new Car();
console.log(myCar instanceof Car);
// console.log(myCar instanceof Vehicle); // Uncommenting this line causes what?Interfaces do not exist at runtime in TypeScript.
instanceof works only with classes and constructor functions at runtime. Since Vehicle is an interface, it is erased during compilation, so myCar instanceof Vehicle causes a compile-time error.
instanceof check return false even though the object is created from the class?class Person {} const obj = { name: "Alice" }; console.log(obj instanceof Person);
The instanceof operator checks if the object was created by the constructor or inherits from its prototype. Here, obj is a plain object literal, not created by Person, so it returns false.
class Cat { meow() { return "meow"; } } class Bird { chirp() { return "chirp"; } } type Pet = Cat | Bird; function speak(pet: Pet) { if (/* condition here */) { return pet.meow(); } else { return pet.chirp(); } }
instanceof checks if pet is an instance of Cat. This narrows the type so pet.meow() is valid. Other options are incorrect because typeof returns 'object' for classes and constructor is a function, not a string.
class A {} class B extends A {} const b = new B(); Object.setPrototypeOf(b, A.prototype); console.log(b instanceof B); console.log(b instanceof A);
By setting b's prototype to A.prototype, b instanceof B becomes false because B.prototype is no longer in the prototype chain. However, b instanceof A is true because A.prototype is now the direct prototype.