TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Destructuring into an empty object vs an object with existing properties yields different results

Open rivatove opened this issue 1 year ago • 3 comments

🔎 Search Terms

"destructuring", "record"

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ.

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.3#code/MYewdgzgLgBATgU1HAJgdQJZQBYGUpwZgDmEAXDAEpIioA80hJANDI0cQHwwC8MA3gF8A3AChRCAB4AHWrFCRYiZOizYAcgFcAtgCMEcclRr12LGGB3643Pv1EwYUggEMACnBDSDUAJ4UABmYHGAA6cOVaVRx8JlJgkSA

💻 Code

This raises a type error:

const recordWithStrings: Record<string, string> = {};

export const recordWithNumbers: Record<string, number> = {
  ...recordWithStrings,
};

and this doesn't:

const recordWithStrings: Record<string, string> = {};

export const recordWithNumbers: Record<string, number> = {
  extraProperty: 0,
  ...recordWithStrings,
};

Is there a sound reason for that?

🙁 Actual behavior

The 2nd example doesn't raise a type error.

🙂 Expected behavior

The 2nd example should raise a type error.

Additional information about the issue

No response

rivatove avatar Oct 31 '24 19:10 rivatove

Maybe related to #27144?

jcalz avatar Oct 31 '24 20:10 jcalz

The reported code is almost an exact copy of what was reported in this comment https://github.com/microsoft/TypeScript/issues/27273#issuecomment-1114703301 and here https://github.com/microsoft/TypeScript/issues/56431 . The last experiment to fix this was worked on here https://github.com/microsoft/TypeScript/pull/56441

Andarist avatar Oct 31 '24 23:10 Andarist

I am facing the same issue. This bug makes spread operator not type-safe.

zanminkian avatar Jun 10 '25 12:06 zanminkian