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

Index Signatures in Object Spreads

How index signatures interact with spreads and when they override or merge with explicit properties.

Index Signatures in Object Spreads

What you'll learn: How index signatures interact with spreads and when they override or merge with explicit properties.

When you spread objects that have index signatures, TypeScript must decide how to combine the index signature's broad "catch-all" type with any explicit properties. The result can sometimes be surprising.

The Core Behavior

An index signature allows an object to have properties beyond those explicitly defined. When you spread such an object, TypeScript merges the index signature into the result type:

type WithIndex = {
  name: string;
  [key: string]: string | number;
};

const obj: WithIndex = { name: "Alice", age: 30 };

const result = { ...obj, active: true };
// Type: { name: string; active: boolean; [key: string]: string | number; }

Notice how active: true became active: boolean, but the index signature [key: string]: string | number remains in the result type. This means TypeScript still allows additional properties of type string | number on result.

Index Signature Constraints Apply

Remember: all explicit properties must satisfy the index signature's type constraint. When spreading, this rule still holds:

const merged = { ...obj, count: 42 };
// ✓ Works: number satisfies string | number

const broken = { ...obj, valid: false };
// ✗ Error: boolean doesn't satisfy string | number from index signature

The index signature from the spread source "infects" the target object, enforcing its constraints on all properties.

Key Takeaway: When spreading objects with index signatures, the index signature propagates to the result type and continues to constrain all properties, including newly added ones.