The in Operator for Object Unions
You'll learn how to use JavaScript's in operator to safely narrow union types containing different object shapes.
What This Solves
When you have a union of object types, each with different properties, TypeScript doesn't know which specific object you're working with. You can't safely access a property that only exists on one type in the union. The in operator lets you check whether a property exists, and TypeScript will narrow the type accordingly.
How It Works
The in operator is a JavaScript feature that checks if a property exists in an object. When TypeScript sees you use it, it understands which type in the union you must have:
type Circle = {
radius: number;
};
type Square = {
sideLength: number;
};
type Shape = Circle | Square;
function getArea(shape: Shape): number {
if ("radius" in shape) {
// TypeScript knows shape is Circle here
return Math.PI * shape.radius * shape.radius;
} else {
// TypeScript knows shape is Square here
return shape.sideLength * shape.sideLength;
}
}
The in operator checks if the property name (as a string) exists in the object. TypeScript sees this and eliminates the types from the union that don't have that property.
Think of It Like a Filter
Imagine sorting mail: if an envelope has a return address from "Circle Co.", you know it's circle-related mail. Similarly, if an object has a radius property, TypeScript knows it must be a Circle, not a Square.
Key Takeaway: Use "propertyName" in object to check for property existence and automatically narrow object union types to the specific shape that contains that property.