Skip to content

Incorrect type checking when object is created using spread operator #60610

@bacher

Description

@bacher

🔎 Search Terms

"object is created using spread operator"
"spread operator type mismatch"
"create object based on another object"
"incorrect inference when spread operator used"

🕗 Version & Regression Information

  • This is the behavior in every version I tried. 5.*, 4.*, 3.*.

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.7.2#code/C4TwDgpgBA0hIDkCGBbaBeKByJWoB9sAjLAbgChyAzAVwDsBjYASwHs6oBzCYAZVbRwQACgCUALljxkaKAG9yUKACceNZRxxlyAX0qhIUACJJgSKJgBKEBq2UATADxCZEADRQAzsGXM6nAD4Kcls6byhWAEZJEzMLeUUoJEksAAsIABsM1iw3RKIUgHc7DPtc3WDQ8NYAJhjTc0wFJQA6Nqi8pQB6LqgAQU9PZk46NDpgL1TWGlKoKiRmDMSAbW4+AQghMQBdSQBWPJ1gnqgAFVTmTygMv2hPKZn7KAhlZTtxclqWpBbgVgBVMCQZQAYSQnggYgoJwAegB+ShfIi-AFAl5giFQ8iwhFAA

💻 Code

type KeyName = 'a' | 'b';

function getSomeKey(): KeyName {
  return 'a';
}

type Data = Record<KeyName, string>;

const o1: Data = {
  a: 'hello',
  b: 'world',
};

const o2: Data = {
  ...o1,
  // Assignment should fail
  [getSomeKey()]: 5,
};

// This line should error:
o2.a.toUpperCase();
// ^?

o2.b.toUpperCase();
// ^?

🙁 Actual behavior

This code snippet effectively puts number 5 into a field, which TS considers a string.

🙂 Expected behavior

const o2: Data = {
  ...o1,
  // Assignment should fail
  [getSomeKey()]: 5,
};

This lines should fail.

Additional information about the issue

This problem reproduced even without using of explicit Record type, example: https://www.typescriptlang.org/play/?ts=5.7.2#code/GYVwdgxgLglg9mABAcwKZQMpwLaoNKoCeAFAJQBciA5AIZWIA+1ARvQN4BQiiATuiDyS0qAbg4BfDhwgIAzlERwAjIgC8iTtxqUqAC1QAbA3CoAaLomY6A7nB4GAJmYmIasxDLDyx0uQrgATGoaFgB04crm3AD00YgAgrKyMMhguGAKsrpwII6IwDQwBhYA2miYOPhEZAC6lACs5uI+sYgAQnBQuorAiF2osqiIWTl5qDw8duQcgaE0oVBwAKoADivjAMJuqGRirQB6APxSs8wLy2ub27scB8dAA

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions