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

Readonly Properties in Object Spreads

What happens to readonly modifiers during spreading and how the resulting type's mutability is determined.

Readonly Properties in Object Spreads

What you'll learn: How TypeScript handles the readonly modifier when you spread objects, and why the result might surprise you.

The Core Behavior

When you spread an object that has readonly properties into a new object literal, TypeScript does not preserve the readonly modifier on the resulting type. The spread operator creates a shallow copy in JavaScript, and TypeScript treats the resulting properties as mutable by default—even if the source had readonly properties.

Think of it like photocopying a document marked "DO NOT EDIT." The photocopy itself doesn't carry that restriction forward; it's a fresh copy that anyone can write on.

How the Type Is Determined

type Source = {
  readonly id: number;
  name: string;
};

const original: Source = { id: 1, name: "Alice" };

const copy = { ...original };
// Type inferred: { id: number; name: string; }
// Notice: 'readonly' is gone!

copy.id = 2; // ✓ Allowed! TypeScript sees 'id' as mutable now

The resulting object's type is inferred from the spread operation itself, not from the source type's modifiers. TypeScript assumes you're creating a new, independent object where properties can be freely modified.

Why This Happens

Spreading is a runtime operation that creates new property descriptors. Since TypeScript's readonly is compile-time only, there's no way to "carry forward" that restriction to a dynamically created object. The type system treats the spread result as a fresh object literal.

Key Takeaway: Spreading an object removes readonly modifiers from the resulting type—the new object's properties are inferred as mutable unless you explicitly annotate otherwise.