0
0
Typescriptprogramming~5 mins

Why instanceof fails on interfaces in Typescript - Quick Recap

Choose your learning style9 modes available
Recall & Review
beginner
What does the instanceof operator check in TypeScript?
<code>instanceof</code> checks if an object is an instance of a specific class or constructor function at runtime.
Click to reveal answer
beginner
Why can't instanceof be used with interfaces in TypeScript?
Interfaces are only a compile-time construct in TypeScript and do not exist in the generated JavaScript code, so instanceof cannot check them at runtime.
Click to reveal answer
intermediate
How can you check if an object implements an interface in TypeScript?
You can check if an object implements an interface by verifying the presence of required properties or methods manually, often called 'duck typing'.
Click to reveal answer
intermediate
What is 'duck typing' in the context of TypeScript interfaces?
'Duck typing' means checking if an object has the necessary properties or methods to be considered of a certain type, rather than checking its actual class or constructor.
Click to reveal answer
intermediate
Can you use instanceof with classes that implement interfaces?
Yes, you can use instanceof with classes because they exist at runtime, but this only checks the class, not the interface itself.
Click to reveal answer
What does instanceof check in TypeScript?
AIf an object is an instance of a class or constructor
BIf an object implements an interface
CIf an object has certain properties
DIf an object is a primitive type
Why does instanceof fail with interfaces?
AInterfaces are primitive types
BInterfaces are removed during compilation and don't exist at runtime
CInterfaces are only for classes
DInterfaces are only used in JavaScript
How can you check if an object matches an interface?
AUsing <code>new</code> keyword
BUsing <code>instanceof</code>
CUsing <code>typeof</code> operator
DChecking if required properties or methods exist
Which of these is true about interfaces in TypeScript?
AThey exist at runtime
BThey are compiled to JavaScript classes
CThey are only used during compile time for type checking
DThey can be checked with <code>instanceof</code>
Can instanceof check if an object is from a class that implements an interface?
AYes, it checks the class, not the interface
BNo, it only checks interfaces
CYes, it checks both class and interface
DNo, it only works with primitives
Explain why the instanceof operator does not work with interfaces in TypeScript.
Think about what exists in the final JavaScript code.
You got /4 concepts.
    Describe how you can check if an object implements an interface in TypeScript without using instanceof.
    Focus on what you can check on the object itself.
    You got /4 concepts.