Consider the following TypeScript code snippet:
interface Animal { name: string; }
class Dog implements Animal { name: string; constructor(name: string) { this.name = name; } }
const pet: Animal = new Dog('Buddy');
console.log(pet instanceof Animal);What will be the output and why?
Think about what instanceof checks at runtime and what interfaces represent in TypeScript.
The instanceof operator checks if an object has a certain constructor in its prototype chain at runtime. Interfaces in TypeScript are only used at compile time for type checking and do not exist in the generated JavaScript code. Therefore, instanceof cannot be used with interfaces and will always return false.
What is the output of this TypeScript code?
interface Vehicle { wheels: number; }
class Car implements Vehicle { wheels = 4; }
const myCar = new Car();
console.log(myCar instanceof Car);
console.log(myCar instanceof Vehicle);Remember that interfaces do not exist at runtime.
myCar instanceof Car returns true because myCar is created from the Car class. However, myCar instanceof Vehicle returns false because Vehicle is an interface and does not exist at runtime.
Look at this TypeScript code:
interface Shape { area(): number; }
class Circle implements Shape {
radius: number;
constructor(radius: number) { this.radius = radius; }
area() { return Math.PI * this.radius * this.radius; }
}
const shape: Shape = new Circle(5);
if (shape instanceof Shape) {
console.log('It is a Shape');
} else {
console.log('Not a Shape');
}Why does it always print 'Not a Shape'?
Think about what instanceof checks and what interfaces represent.
instanceof checks the prototype chain for a constructor function. Interfaces are only a compile-time construct and do not exist in the JavaScript output, so instanceof Shape always returns false.
Which of the following TypeScript code snippets will cause a runtime error when executed?
Consider what values can be used with instanceof without causing errors.
Using instanceof with null causes a runtime TypeError because null is not an object and cannot have a prototype chain.
Since instanceof does not work with interfaces in TypeScript, which approach below correctly checks if an object implements the Logger interface at runtime?
interface Logger { log(message: string): void; }Interfaces do not exist at runtime, so you must check properties manually.
Because interfaces are erased during compilation, you cannot use instanceof or typeof to check for them. Instead, checking if the object has the required method with the correct type is the common runtime approach.