What if your code could instantly know exactly what kind of object it's dealing with, without any guesswork?
Why instanceof type guards in Typescript? - Purpose & Use Cases
Imagine you have a box full of different toys: cars, dolls, and balls. You want to play only with the cars, but you have to check each toy by guessing its type before you can play. This guessing is like manually checking each object's type in your code.
Manually checking types means writing many if-else statements, which can be slow and confusing. It's easy to make mistakes, like mixing up types or missing some cases. This makes your code messy and hard to fix later.
Using instanceof type guards lets your program automatically check an object's type safely and clearly. It helps the computer understand what kind of object it is working with, so you can use the right properties and methods without guessing.
if (obj.type === 'Car') { // use car methods } else if (obj.type === 'Doll') { // use doll methods }
if (obj instanceof Car) { // use car methods } else if (obj instanceof Doll) { // use doll methods }
This makes your code safer and easier to read, letting you work confidently with different object types without errors.
Think of a game where you have different characters like knights and wizards. Using instanceof type guards, the game knows exactly which character you picked and what special moves you can use.
Manual type checks are slow and error-prone.
instanceof type guards automate and simplify type checking.
This leads to safer, clearer, and more reliable code.
Practice
instanceof operator check in TypeScript?Solution
Step 1: Understand the purpose of
Theinstanceofinstanceofoperator checks whether an object was created from a particular class.Step 2: Differentiate from other checks
It does not check primitive types, function returns, or interfaces, only class instances.Final Answer:
If an object is an instance of a specific class -> Option BQuick Check:
instanceofchecks class instance = A [OK]
- Thinking instanceof works with interfaces
- Confusing instanceof with typeof
- Assuming instanceof checks primitive types
obj is an instance of class Car?Solution
Step 1: Recall correct
The correct syntax uses the keywordinstanceofsyntaxinstanceofbetween the object and the class name.Step 2: Identify invalid options
Options B, C, and D use incorrect keywords or missing syntax.Final Answer:
if (obj instanceof Car) { } -> Option AQuick Check:
Correct syntax uses instanceof keyword = A [OK]
- Using 'is' or 'type' instead of 'instanceof'
- Omitting parentheses around condition
- Writing 'instance' instead of 'instanceof'
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()));Solution
Step 1: Identify the object passed
The functionspeakis called withnew Cat(), soanimalis a Cat instance.Step 2: Check the instanceof condition
The conditionanimal instanceof Dogis false, so the else block runs, returninganimal.meow().Final Answer:
'meow' -> Option CQuick Check:
Cat instance triggers else block = D [OK]
- Assuming instanceof works with interfaces
- Confusing which method runs for which class
- Expecting 'woof' when passing Cat instance
interface Bird { fly(): void; }
class Eagle implements Bird { fly() { console.log('Flying'); } }
function check(bird: Bird) {
if (bird instanceof Eagle) {
bird.fly();
}
}Solution
Step 1: Understand instanceof usage
Theinstanceofoperator is used with the classEagle, which is valid even thoughbirdis typed as the interfaceBird.Step 2: Verify no errors
There are no syntax errors, type mismatches, or runtime issues. TypeScript compiles this code and narrowsbirdtoEagleinside theifblock.Final Answer:
No error, code is correct -> Option AQuick Check:
instanceof with class on interface-typed param works = D [OK]
- Thinking instanceof can't be used on interface-typed variables
- Confusing instanceof with direct interface checks
- Thinking implementing class must be abstract
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?Solution
Step 1: Check instanceof order and method calls
The function must check ifanimalis aFishorBirdusinginstanceofand call the correct method.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 checksFishfirst, callsswim(), thenBirdwithfly(), 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 checksAnimalfirst, 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.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 DQuick Check:
Correct instanceof checks and method calls = B [OK]
- Checking base class first, blocking subclass checks
- Calling wrong methods for classes
- Returning strings instead of calling methods
Ready to prove it?
Pass the test and this pattern moves unknown
