Narrowing Object Unions with in
What you'll learn: How to use the in operator to safely distinguish between different object types in a union by checking for their unique properties.
The Core Idea
When you have a union of object types, TypeScript doesn't automatically know which variant you're working with. The in operator lets you check if a specific property exists on an object, and TypeScript uses that information to narrow the type.
Think of it like checking someone's credentials: if they have a pilot's license, they're a pilot; if they have a medical license, they're a doctor. The presence of a unique property tells you what you're dealing with.
How It Works
When you use in in a conditional check, TypeScript understands that inside the if block, the object must be the variant that has that property:
type Cat = { meow: () => void; whiskers: number };
type Dog = { bark: () => void; breed: string };
function handlePet(pet: Cat | Dog) {
if ('meow' in pet) {
// TypeScript knows pet is Cat here
pet.meow();
} else {
// TypeScript knows pet is Dog here
pet.bark();
}
}
The in operator returns true if the property exists on the object, which both JavaScript understands at runtime and TypeScript uses for type narrowing at compile time.
When to Use It
Use in narrowing when each variant in your union has at least one unique property. This works for discriminating between shapes, API responses, configuration objects, or any union where object structure differs.
Key Takeaway: The in operator lets you narrow object unions by checking for the presence of unique properties, giving you type-safe access to variant-specific fields.