0
0
Typescriptprogramming~20 mins

instanceof type guards in Typescript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Instanceof Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of instanceof with class inheritance
What is the output of the following TypeScript code?
Typescript
class Animal {}
class Dog extends Animal {}

const pet = new Dog();

console.log(pet instanceof Dog);
console.log(pet instanceof Animal);
Afalse\nfalse
Btrue\nfalse
Cfalse\ntrue
Dtrue\ntrue
Attempts:
2 left
💡 Hint
Remember that instanceof checks the prototype chain.
Predict Output
intermediate
2:00remaining
instanceof with interface and class
Given the code below, what will be the output?
Typescript
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?
Atrue\nfalse
Btrue\nCompile-time error
Ctrue\nTypeError
Dtrue\nSyntaxError
Attempts:
2 left
💡 Hint

Interfaces do not exist at runtime in TypeScript.

🔧 Debug
advanced
2:00remaining
Why does this instanceof check fail?
Consider the following code. Why does the instanceof check return false even though the object is created from the class?
Typescript
class Person {}

const obj = { name: "Alice" };

console.log(obj instanceof Person);
ABecause obj is a plain object, not created with Person constructor
BBecause Person class is not exported
CBecause instanceof only works with interfaces
DBecause obj has no name property
Attempts:
2 left
💡 Hint
Think about how instanceof works with prototypes.
🧠 Conceptual
advanced
2:00remaining
Using instanceof in type guards with union types
Given the classes below, which option correctly narrows the type using instanceof in a function?
Typescript
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();
  }
}
Apet instanceof Cat
Bpet instanceof Bird
Ctypeof pet === 'Cat'
Dpet.constructor === 'Cat'
Attempts:
2 left
💡 Hint
Use instanceof to check class type at runtime.
Predict Output
expert
3:00remaining
Output of instanceof with prototype manipulation
What is the output of this TypeScript code?
Typescript
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);
Atrue\ntrue
Bfalse\nfalse
Cfalse\ntrue
Dtrue\nfalse
Attempts:
2 left
💡 Hint
Changing the prototype affects instanceof checks.