Recall & Review
beginner
What does the
instanceof operator do in TypeScript?It checks if an object is an instance of a specific class or constructor function, helping TypeScript narrow the type within a conditional block.Click to reveal answer
beginner
How does
instanceof help with type safety?By verifying an object's class at runtime, <code>instanceof</code> lets TypeScript know the exact type, so you can safely access properties or methods specific to that class.Click to reveal answer
beginner
Example: What type does TypeScript infer inside this block?<br>
if (obj instanceof Date) {<br> // What type is obj here?<br>}Inside the block, TypeScript knows
obj is a Date object, so you can use Date methods safely.Click to reveal answer
intermediate
Can
instanceof be used with interfaces in TypeScript?No, because interfaces do not exist at runtime.
instanceof works only with classes or constructor functions that exist when the code runs.Click to reveal answer
intermediate
Why might you prefer
instanceof over checking a property manually?Because
instanceof is a built-in, reliable way to check an object's type, reducing errors and making your code clearer and easier to maintain.Click to reveal answer
What does
obj instanceof ClassName check?✗ Incorrect
instanceof checks if the object was created by the class or inherits from it.
Can
instanceof be used to check if an object implements an interface?✗ Incorrect
Interfaces do not exist at runtime, so instanceof cannot check them.
Inside
if (obj instanceof Date) { ... }, what type does TypeScript assume for obj?✗ Incorrect
TypeScript narrows obj to Date inside the block.
Which of these is a correct use of
instanceof?✗ Incorrect
Array is a class, so instanceof works. Primitive types like string, number, boolean are not classes.
Why is
instanceof preferred over checking a property like obj.type === 'Date'?✗ Incorrect
instanceof checks the real prototype chain, making it more reliable than property checks.
Explain how
instanceof helps TypeScript narrow types during runtime checks.Think about how JavaScript knows an object's class.
You got /4 concepts.
Why can't
instanceof be used with interfaces in TypeScript? What alternative can you use to check types related to interfaces?Interfaces disappear after compiling to JavaScript.
You got /3 concepts.