Course contentsShow
← TypeScript
Lesson 330 of 1,7967. ObjectsFree lesson

Object Spread Basics and Type Inference

How TypeScript infers types when spreading objects and what properties the resulting type contains.

Object Spread Basics and Type Inference

You'll learn how TypeScript determines the type of a new object created with the spread operator (...).

How Object Spread Works

When you spread one or more objects into a new object literal, TypeScript merges their types intelligently. The resulting type contains all properties from the spread objects, with later spreads overriding earlier ones if there are conflicts.

const coords = { x: 10, y: 20 };
const point = { ...coords, z: 30 };
// Type inferred: { x: number; y: number; z: number }

TypeScript sees that point has all the properties from coords plus the new z property.

Property Override Behavior

When spreading multiple objects with overlapping properties, the rightmost (last) spread wins in both value and type:

const base = { name: "Alice", age: 25 };
const override = { age: 30, role: "Developer" };
const merged = { ...base, ...override };
// Type inferred: { name: string; age: number; role: string }
// age comes from override, not base

The property order in the resulting type reflects the final shape after all spreads are applied.

Mixing Spread with Direct Properties

You can combine spread operations with directly declared properties. Direct properties override spread properties if they share the same key:

const settings = { theme: "dark", notifications: true };
const custom = { ...settings, theme: "light" };
// Type inferred: { theme: string; notifications: boolean }
// theme is overridden to "light"

Key Takeaway: TypeScript infers the spread object's type by merging all spread source types and any additional properties, with later properties overriding earlier ones when keys conflict.