Skip to content

Nested object spread destructuring doesn't remove readonly-ness #53917

@pschiffmann

Description

@pschiffmann

Bug Report

The two functions below behave identical at runtime. However, TypeScript flags the second function with an error.

interface Data {
  readonly nested: Readonly<Record<string, string>>;
}

function updateNested_1(data: Data, k: string, v: string): Data {
  const nested = { ...testData.nested };
  nested[k] = v;
  return { ...data, nested };
}

function updateNested_2(data: Data, k: string, v: string): Data {
  const {
    nested: { ...nested },
  } = data;
  nested[k] = v; // Index signature in type '{ readonly [x: string]: string; }' only permits reading.ts(2542)
  return { ...data, nested };
}

🔎 Search Terms

destruct readonly

🕗 Version & Regression Information

Tested in version 5.0.4.

⏯ Playground Link

Playground Link

🙁 Actual behavior

Since the spread-destructuring creates a copy of the original object, it should lose it's readonly modifier.

🙂 Expected behavior

The spread-destructured object retains it's readonly modifier.

Interestingly, this works already if nested doesn't have an index signature.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Not a DefectThis behavior is one of several equally-correct options

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions