Spreading Union Types
You'll learn: How TypeScript handles object spreads when the source object is a union type, and what the resulting type looks like.
The Core Problem
When you spread an object that could be one of several types (a union), TypeScript needs to figure out what properties the resulting object will definitely have. The challenge: different branches of the union might have completely different properties.
How TypeScript Handles It
TypeScript creates a union of all possible spread outcomes. If you spread a union type A | B, the result is the union of what you'd get from spreading A separately and spreading B separately.
Here's the key: TypeScript considers each possibility independently:
type Circle = { kind: "circle"; radius: number };
type Square = { kind: "square"; size: number };
type Shape = Circle | Square;
const shape: Shape = { kind: "circle", radius: 10 };
const defaults = { color: "red" };
const result = { ...defaults, ...shape };
// Type: { color: string } & Circle | { color: string } & Square
The result type is a union representing both possibilities: it could be { color: string, kind: "circle", radius: number } OR { color: string, kind: "square", size: number }.
Why This Matters
You can't access properties that don't exist on all union members:
// Error: Property 'radius' doesn't exist on all types
// result.radius
if (result.kind === "circle") {
result.radius; // OK after narrowing
}
Key Takeaway: Spreading a union type produces a union of spread results—TypeScript preserves all possibilities rather than merging them, requiring type narrowing to access branch-specific properties.