0
0
Typescriptprogramming~5 mins

instanceof type guards in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AIf obj is created by ClassName or inherits from it
BIf obj has a property named ClassName
CIf obj is equal to ClassName
DIf obj is a primitive type
Can instanceof be used to check if an object implements an interface?
AOnly if the interface has a constructor
BYes, always
CNo, interfaces are erased at runtime
DOnly in strict mode
Inside if (obj instanceof Date) { ... }, what type does TypeScript assume for obj?
ADate
Bany
CObject
Dunknown
Which of these is a correct use of instanceof?
Aif (value instanceof string) { ... }
Bif (value instanceof boolean) { ... }
Cif (value instanceof number) { ... }
Dif (value instanceof Array) { ... }
Why is instanceof preferred over checking a property like obj.type === 'Date'?
ABecause <code>instanceof</code> is faster
BBecause <code>instanceof</code> checks the actual prototype chain
CBecause properties can never be trusted
DBecause <code>instanceof</code> works with primitives
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.