The instanceof Operator Basics
What you'll learn: How TypeScript uses the instanceof operator to narrow types by checking if an object belongs to a specific class.
What instanceof Does
While typeof checks primitive types and in checks for property existence, instanceof answers a different question: "Is this object an instance of this class?" It walks up JavaScript's prototype chain at runtime to verify that a value was created by (or inherited from) a particular constructor function or class.
How instanceof Works
The instanceof operator takes two operands: a value on the left and a constructor/class on the right. It returns true if the value's prototype chain includes that constructor's prototype.
class Dog {
bark() {
console.log("Woof!");
}
}
class Cat {
meow() {
console.log("Meow!");
}
}
function handlePet(pet: Dog | Cat) {
if (pet instanceof Dog) {
// TypeScript narrows type to Dog here
pet.bark();
} else {
// TypeScript knows pet must be Cat here
pet.meow();
}
}
Why This Matters for Type Narrowing
Unlike typeof (which only recognizes built-in types like "string" or "object"), instanceof distinguishes between your custom classes. TypeScript's control flow analysis understands instanceof checks and automatically narrows the type within the guarded block.
This works because instanceof is a runtime check that TypeScript trusts for compile-time narrowing.
Key Takeaway: The instanceof operator checks if a value belongs to a specific class by inspecting its prototype chain, allowing TypeScript to narrow union types to specific class instances.