Bird
Raised Fist0
Typescriptprogramming~10 mins

instanceof type guards in Typescript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - instanceof type guards
Start with variable
↓
Check: variable instanceof Class?
No→Else branch
Yes↓
Inside if: variable treated as Class type
↓
Use variable with Class properties/methods
↓
End
The program checks if a variable is an instance of a class. If yes, it treats the variable as that class type inside the if block.
Execution Sample
Typescript
class Cat {
  meow() { return 'meow'; }
}

const pet = new Cat();

if (pet instanceof Cat) {
  console.log(pet.meow());
}
This code checks if pet is an instance of Cat, then calls the meow method safely.
Execution Table
StepActionEvaluationResult
1Create class CatN/AClass Cat defined
2Create pet = new Cat()pet instanceof Cattrue
3Check if pet instanceof CattrueEnter if block
4Call pet.meow()pet.meow()'meow' printed
5EndN/AProgram ends
💡 No exit from if because pet is instance of Cat
Variable Tracker
VariableStartAfter 1After 2Final
petundefinedCat instanceCat instanceCat instance
Key Moments - 2 Insights
Why can we call pet.meow() inside the if block?
Because the instanceof check (see step 3 in execution_table) confirms pet is a Cat, so TypeScript knows pet has the meow method.
What happens if pet is not an instance of Cat?
The if condition fails (step 3), so the code inside the if block does not run, preventing errors from calling meow on a wrong type.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the result of 'pet instanceof Cat' at step 2?
Aundefined
Bfalse
Ctrue
Derror
💡 Hint
Check the 'Evaluation' column at step 2 in execution_table
At which step does the program enter the if block?
AStep 1
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Result' column in execution_table for step 3
If pet was not an instance of Cat, what would happen to the call pet.meow()?
AIt would be skipped because the if block is not entered
BIt would run normally
CIt would cause a runtime error
DIt would print undefined
💡 Hint
Refer to key_moments about what happens if instanceof check fails
Concept Snapshot
instanceof type guards check if a variable is an instance of a class.
Syntax: if (variable instanceof Class) { /* variable treated as Class */ }
Inside the if block, TypeScript knows the variable has Class properties/methods.
Prevents errors by narrowing types safely at runtime.
Full Transcript
This visual trace shows how instanceof type guards work in TypeScript. First, a class Cat is defined. Then, a variable pet is created as an instance of Cat. The program checks if pet is an instance of Cat using 'pet instanceof Cat'. Since this is true, the code inside the if block runs, allowing safe use of pet.meow(). The variable tracker shows pet starts undefined and becomes a Cat instance. Key moments explain why the method call is safe and what happens if the check fails. The quizzes test understanding of the instanceof check result, when the if block runs, and behavior if the check fails.

Practice

(1/5)
1. What does the instanceof operator check in TypeScript?
easy
A. If a variable is a primitive type
B. If an object is an instance of a specific class
C. If a function returns a boolean
D. If a type is an interface

Solution

  1. Step 1: Understand the purpose of instanceof

    The instanceof operator checks whether an object was created from a particular class.
  2. Step 2: Differentiate from other checks

    It does not check primitive types, function returns, or interfaces, only class instances.
  3. Final Answer:

    If an object is an instance of a specific class -> Option B
  4. Quick Check:

    instanceof checks class instance = A [OK]
Hint: Remember: instanceof works only with classes, not interfaces [OK]
Common Mistakes:
  • Thinking instanceof works with interfaces
  • Confusing instanceof with typeof
  • Assuming instanceof checks primitive types
2. Which of the following is the correct syntax to check if obj is an instance of class Car?
easy
A. if (obj instanceof Car) { }
B. if (obj instance Car) { }
C. if (obj is Car) { }
D. if (obj type Car) { }

Solution

  1. Step 1: Recall correct instanceof syntax

    The correct syntax uses the keyword instanceof between the object and the class name.
  2. Step 2: Identify invalid options

    Options B, C, and D use incorrect keywords or missing syntax.
  3. Final Answer:

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

    Correct syntax uses instanceof keyword = A [OK]
Hint: Use 'instanceof' keyword exactly between object and class [OK]
Common Mistakes:
  • Using 'is' or 'type' instead of 'instanceof'
  • Omitting parentheses around condition
  • Writing 'instance' instead of 'instanceof'
3. What will be the output of this code?
class Dog { bark() { return 'woof'; } }
class Cat { meow() { return 'meow'; } }
function speak(animal: Dog | Cat) {
if (animal instanceof Dog) {
return animal.bark();
} else {
return animal.meow();
}
}
console.log(speak(new Cat()));
medium
A. 'woof'
B. TypeError at runtime
C. 'meow'
D. undefined

Solution

  1. Step 1: Identify the object passed

    The function speak is called with new Cat(), so animal is a Cat instance.
  2. Step 2: Check the instanceof condition

    The condition animal instanceof Dog is false, so the else block runs, returning animal.meow().
  3. Final Answer:

    'meow' -> Option C
  4. Quick Check:

    Cat instance triggers else block = D [OK]
Hint: Trace instanceof condition to pick correct method call [OK]
Common Mistakes:
  • Assuming instanceof works with interfaces
  • Confusing which method runs for which class
  • Expecting 'woof' when passing Cat instance
4. Identify the error in this code snippet:
interface Bird { fly(): void; }
class Eagle implements Bird { fly() { console.log('Flying'); } }
function check(bird: Bird) {
if (bird instanceof Eagle) {
bird.fly();
}
}
medium
A. No error, code is correct
B. Missing return type in fly() method
C. Cannot use instanceof with interfaces
D. Eagle class must be abstract

Solution

  1. Step 1: Understand instanceof usage

    The instanceof operator is used with the class Eagle, which is valid even though bird is typed as the interface Bird.
  2. Step 2: Verify no errors

    There are no syntax errors, type mismatches, or runtime issues. TypeScript compiles this code and narrows bird to Eagle inside the if block.
  3. Final Answer:

    No error, code is correct -> Option A
  4. Quick Check:

    instanceof with class on interface-typed param works = D [OK]
Hint: Remember: instanceof works with classes even on interface-typed variables [OK]
Common Mistakes:
  • Thinking instanceof can't be used on interface-typed variables
  • Confusing instanceof with direct interface checks
  • Thinking implementing class must be abstract
5. Given these classes:
class Animal { name: string; constructor(name: string) { this.name = name; } }
class Fish extends Animal { swim() { return 'swimming'; } }
class Bird extends Animal { fly() { return 'flying'; } }

Write a function move that takes animal: Animal and returns 'swimming' if it's a Fish, 'flying' if it's a Bird, or 'unknown' otherwise. Which implementation is correct?
hard
A. function move(animal: Animal) { if (animal instanceof Animal) return 'unknown'; else if (animal instanceof Fish) return animal.swim(); else return animal.fly(); }
B. function move(animal: Animal) { if (animal instanceof Fish) return 'flying'; else if (animal instanceof Bird) return 'swimming'; else return 'unknown'; }
C. function move(animal: Animal) { if (animal instanceof Fish) return animal.fly(); else if (animal instanceof Bird) return animal.swim(); else return 'unknown'; }
D. function move(animal: Animal) { if (animal instanceof Fish) return animal.swim(); else if (animal instanceof Bird) return animal.fly(); else return 'unknown'; }

Solution

  1. Step 1: Check instanceof order and method calls

    The function must check if animal is a Fish or Bird using instanceof and call the correct method.
  2. Step 2: Validate each option

    function move(animal: Animal) { if (animal instanceof Fish) return animal.swim(); else if (animal instanceof Bird) return animal.fly(); else return 'unknown'; } correctly checks Fish first, calls swim(), then Bird with fly(), else returns 'unknown'. function move(animal: Animal) { if (animal instanceof Animal) return 'unknown'; else if (animal instanceof Fish) return animal.swim(); else return animal.fly(); } wrongly checks Animal first, which always matches. function move(animal: Animal) { if (animal instanceof Fish) return animal.fly(); else if (animal instanceof Bird) return animal.swim(); else return 'unknown'; } swaps methods incorrectly. function move(animal: Animal) { if (animal instanceof Fish) return 'flying'; else if (animal instanceof Bird) return 'swimming'; else return 'unknown'; } returns incorrect strings directly without calling methods.
  3. Final Answer:

    function move(animal: Animal) { if (animal instanceof Fish) return animal.swim(); else if (animal instanceof Bird) return animal.fly(); else return 'unknown'; } -> Option D
  4. Quick Check:

    Correct instanceof checks and method calls = B [OK]
Hint: Check instanceof order and call matching methods [OK]
Common Mistakes:
  • Checking base class first, blocking subclass checks
  • Calling wrong methods for classes
  • Returning strings instead of calling methods
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