What is the difference between typeof, instanceof and the in operator for narrowing?
typeof narrows primitives like string and number, instanceof narrows class instances by checking the prototype chain, and in narrows object types by checking whether a property name exists. Pick the one that matches what makes the types different.
Explain it simply
Three ways to identify a person at a gate. typeof checks the kind of thing: is this a string or a number? instanceof checks which class made it, like asking which college issued the ID card. in checks whether a particular feature is present, like looking for a name badge.
Each one tells TypeScript enough to treat the value as a narrower type inside the if block. Note that typeof null is "object", so typeof alone does not rule out null.
Example
function size(x: string | number[]): number {
if (typeof x === "string") return x.length; // x: string
return x.length; // x: number[]
}
class Car { drive() {} }
class Bike { ride() {} }
function go(v: Car | Bike) {
if (v instanceof Car) v.drive(); // v: Car
else v.ride(); // v: Bike
}
type Cat = { meow(): void };
type Dog = { bark(): void };
function speak(p: Cat | Dog) {
if ("meow" in p) p.meow(); // p: Cat
else p.bark(); // p: Dog
}What to say in the interview
"typeof is for primitives, instanceof is for class instances, and in is for plain object shapes that differ by a property. All three act as type guards, so inside the branch TypeScript knows the narrower type. For plain data without classes I prefer in or a discriminant property."
Common mistakes
- Using instanceof on interfaces or type aliases; they do not exist at runtime.