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

Common Spread Pitfalls and Solutions

Typical type errors with object spreads like excess properties and how to resolve them correctly.

Common Spread Pitfalls and Solutions

What you'll learn: The typical type errors that occur when spreading objects in TypeScript and how to fix them correctly.

Understanding the Problems

Object spreading is powerful, but it comes with type-safety traps. The most common pitfall involves excess properties: when you spread objects together, TypeScript might accept properties that shouldn't exist according to your type definitions, or reject valid spreads due to strict checks.

Think of it like mixing paint colors — sometimes you get exactly what you expect, and sometimes unexpected properties "bleed through" in ways that violate your type contracts.

Common Pitfall #1: Excess Properties After Spread

type Config = { debug: boolean };

const base: Config = { debug: false };

// Error: excess property 'verbose'
const extended: Config = { 
  ...base, 
  verbose: true  // ❌ Not allowed in Config
};

Solution: Either add the property to your type or use a different type:

// Option 1: Update the type
type Config = { debug: boolean; verbose?: boolean };

// Option 2: Use a wider variable first
const partial = { ...base, verbose: true };
const extended: Config = { debug: partial.debug };

Common Pitfall #2: Lost Property Types

When spreading without annotations, you might lose readonly or optional modifiers:

type Original = { readonly id: number };
const obj: Original = { id: 1 };

const copy = { ...obj };  // copy.id is NOT readonly anymore

Solution: Explicitly type the result if you need to preserve constraints.

Key Takeaway: Object spreads bypass excess property checks when using intermediate variables, and they don't preserve readonly/optional modifiers unless you explicitly annotate the result type — be intentional about when you rely on inference versus annotations after spreading.