Bird
Raised Fist0
Typescriptprogramming~10 mins

Why instanceof fails on interfaces in Typescript - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why instanceof fails on interfaces
Create Interface
↓
Create Class implementing Interface
↓
Create Object from Class
↓
Use instanceof to check Interface
↓
Fails: instanceof only works with Classes
↓
Use alternative: 'in' operator or user-defined type guards
This flow shows that instanceof works only with classes, not interfaces, so checking interface types with instanceof fails.
Execution Sample
Typescript
interface IAnimal { speak(): void; }
class Dog implements IAnimal {
  speak() { console.log('Woof'); }
}
const pet = new Dog();
console.log(pet instanceof IAnimal);
This code tries to check if pet is an instance of interface IAnimal using instanceof, which fails.
Execution Table
StepActionEvaluationResult
1Define interface IAnimalN/AInterface created, no runtime code
2Define class Dog implementing IAnimalN/AClass Dog created with speak method
3Create object pet = new Dog()N/Apet is an instance of Dog
4Evaluate pet instanceof IAnimalpet instanceof IAnimalError or false, because IAnimal is not a class
5Use alternative check: 'speak' in pet'speak' in pettrue, pet has speak method
💡 instanceof fails because interfaces do not exist at runtime, only classes do
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5
petundefinedDog instanceN/A (instanceof check fails)Dog instance
Key Moments - 2 Insights
Why does 'pet instanceof IAnimal' fail even though Dog implements IAnimal?
Because interfaces are only a compile-time construct and do not exist in the JavaScript runtime, instanceof can only check against classes, not interfaces. See execution_table step 4.
How can I check if an object implements an interface at runtime?
You can check if the object has the required properties or methods using the 'in' operator or user-defined type guards, as shown in execution_table step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result of 'pet instanceof IAnimal' at step 4?
Atrue
Bfalse or error
Cundefined
Dpet object
💡 Hint
Check execution_table row 4 under Result column
At which step does the object 'pet' get created as an instance of Dog?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at execution_table row 3 describing object creation
If you want to check if 'pet' has a 'speak' method, which step shows a working approach?
AStep 5
BStep 2
CStep 4
DStep 1
💡 Hint
See execution_table row 5 for alternative check using 'in' operator
Concept Snapshot
instanceof checks only work with classes at runtime
Interfaces are compile-time only and do not exist in JavaScript
Checking interface implementation with instanceof fails
Use 'in' operator or custom type guards to check interface shape
Classes create real objects; interfaces do not
Remember: instanceof needs a constructor function
Full Transcript
In TypeScript, interfaces are only used during compilation to check types. They do not exist in the JavaScript code that runs. The instanceof operator checks if an object was created by a specific class constructor. Since interfaces have no constructor at runtime, using instanceof with an interface always fails or returns false. Instead, to check if an object matches an interface, you can check if it has the required properties or methods using the 'in' operator or write custom type guard functions. This visual trace shows defining an interface, a class implementing it, creating an object, and then trying instanceof which fails. Finally, it shows a working alternative using the 'in' operator.

Practice

(1/5)
1. Why does the instanceof operator fail when used to check if an object implements a TypeScript interface?
easy
A. Because interfaces are only used for styling in TypeScript.
B. Because instanceof only works with primitive types.
C. Because interfaces do not exist at runtime in JavaScript.
D. Because instanceof requires a function as the right operand.

Solution

  1. Step 1: Understand what instanceof checks

    The instanceof operator checks if an object was created from a specific class or constructor function at runtime.
  2. Step 2: Recognize interface behavior in TypeScript

    Interfaces in TypeScript are only used during compilation and do not exist in the generated JavaScript code, so instanceof cannot check them.
  3. Final Answer:

    Because interfaces do not exist at runtime in JavaScript. -> Option C
  4. Quick Check:

    Interfaces disappear at runtime = A [OK]
Hint: Remember: interfaces vanish after compile, so instanceof fails [OK]
Common Mistakes:
  • Thinking instanceof works with interfaces
  • Confusing interfaces with classes
  • Assuming interfaces exist at runtime
  • Using instanceof with primitives
2. Which of the following is the correct syntax to check if an object is an instance of a class Person in TypeScript?
easy
A. if (obj instanceof Person) { }
B. if (obj instanceof 'Person') { }
C. if (obj instanceof InterfacePerson) { }
D. if (obj instanceof { name: string }) { }

Solution

  1. Step 1: Recall instanceof syntax

    The right side of instanceof must be a class or constructor function, not a string or interface.
  2. Step 2: Identify valid usage

    Only obj instanceof Person is valid syntax to check if obj is created from class Person.
  3. Final Answer:

    if (obj instanceof Person) { } -> Option A
  4. Quick Check:

    Right operand must be class/constructor = C [OK]
Hint: Use class name without quotes for instanceof [OK]
Common Mistakes:
  • Using interface names with instanceof
  • Putting class name in quotes
  • Using object literals on right side
  • Confusing type and value syntax
3. Consider this TypeScript code:
interface Animal { name: string }
class Dog implements Animal { constructor(public name: string) {} }
const pet = new Dog('Buddy');
console.log(pet instanceof Dog);
console.log(pet instanceof Animal);

What is the output?
medium
A. false\nfalse
B. true\ntrue
C. false\ntrue
D. true\nfalse

Solution

  1. Step 1: Check pet instanceof Dog

    Since pet was created with new Dog(), this returns true.
  2. Step 2: Check pet instanceof Animal

    Animal is an interface and does not exist at runtime, so this returns false.
  3. Final Answer:

    true\nfalse -> Option D
  4. Quick Check:

    Class instance true, interface instance false = A [OK]
Hint: Only classes work with instanceof, interfaces do not [OK]
Common Mistakes:
  • Expecting interface check to return true
  • Confusing interface with class
  • Assuming interfaces exist at runtime
  • Misreading output order
4. Given this code snippet:
interface Vehicle { wheels: number }
function isVehicle(obj: any) {
  return obj instanceof Vehicle;
}

Why does this code cause an error or unexpected behavior?
medium
A. Because Vehicle is an interface and cannot be used with instanceof.
B. Because obj is not typed correctly.
C. Because instanceof requires a string argument.
D. Because Vehicle is not imported.

Solution

  1. Step 1: Identify the use of instanceof with interface

    The code uses instanceof with Vehicle, which is an interface.
  2. Step 2: Understand interface runtime behavior

    Interfaces do not exist at runtime, so instanceof Vehicle is invalid and causes an error or always returns false.
  3. Final Answer:

    Because Vehicle is an interface and cannot be used with instanceof. -> Option A
  4. Quick Check:

    Interfaces can't be checked with instanceof = D [OK]
Hint: Never use instanceof with interfaces, only classes [OK]
Common Mistakes:
  • Trying to check interfaces with instanceof
  • Ignoring runtime absence of interfaces
  • Assuming instanceof works with types
  • Misunderstanding error cause
5. You want to check at runtime if an object matches the shape of an interface Person { name: string; age: number; }. Since instanceof does not work with interfaces, which approach is best?
hard
A. Use instanceof Person anyway; it will work after compilation.
B. Manually check if object has required properties with correct types.
C. Convert the interface to a class and use instanceof.
D. Use typeof obj === 'Person' to check the type.

Solution

  1. Step 1: Understand interface runtime absence

    Interfaces do not exist at runtime, so instanceof or typeof cannot check them directly.
  2. Step 2: Choose property checks for runtime validation

    The best way is to manually check if the object has the required properties with the expected types.
  3. Final Answer:

    Manually check if object has required properties with correct types. -> Option B
  4. Quick Check:

    Manual property checks replace instanceof for interfaces = B [OK]
Hint: Check properties manually to mimic interface checks at runtime [OK]
Common Mistakes:
  • Using instanceof with interfaces
  • Assuming typeof works for interfaces
  • Converting interfaces to classes unnecessarily
  • Ignoring runtime type checks
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard