What You'll Learn
You'll learn how to pick the right narrowing operator by matching it to what you're checking: primitives, object properties, or class instances.
The Right Tool for the Right Job
TypeScript gives you three main narrowing operators, and each one shines in different situations. Think of them like different keys on your keyring — they all unlock type safety, but each fits a specific lock.
Use typeof for Primitives
When you need to distinguish between string, number, boolean, bigint, symbol, or function, reach for typeof. It's your go-to for checking JavaScript's basic types:
function process(value: string | number) {
if (typeof value === "string") {
// value is string here
}
}
Use in for Object Property Detection
When you have union types where objects have different properties, use the in operator. It checks whether a property exists on an object:
type Cat = { meow: () => void };
type Dog = { bark: () => void };
function speak(animal: Cat | Dog) {
if ("meow" in animal) {
// animal is Cat here
}
}
Use instanceof for Class Hierarchies
When working with class instances or built-in constructors like Date, Error, or Array, use instanceof. It checks the prototype chain:
function handle(error: Error | string) {
if (error instanceof Error) {
// error is Error here
}
}
Quick Decision Guide
- Primitive types? →
typeof - Object with specific properties? →
in - Class instance or constructor? →
instanceof
Key Takeaway: Match your narrowing operator to what you're checking — typeof for primitives, in for object properties, and instanceof for classes — to write clear, effective type guards.