Microsoft/TypeScript

Inconsistent key type inference when spreading objects with const assertion into plain objects

Open

#59,102 opened on 2024幎7月2日

GitHub で芋る
 (3 comments) (0 reactions) (0 assignees)TypeScript (6,726 forks)batch import
Domain: check: Type InferenceHelp WantedPossible Improvement

Repository metrics

Stars
 (48,455 stars)
PR merge metrics
 (平均マヌゞ 6d 17h) (30d で 9 merged PRs)

説明

🔎 Search Terms

const assertion, type inference, as const, object keys, type conversion, keyof typeof, satisfies, spread, readonly object

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about keyof, as const, infererence etc.

⏯ Playground Link

Playground

💻 Code

const namesById = {
  1: "John Doe",
  2: "Jane Smith",
  3: "Alex Johnson",
  4: "Maria Garcia",
} as const satisfies Record<number, string>;

type Ids = keyof typeof namesById;
//   ^? type Ids = 1 | 2 | 3 | 4

const namesByIdCopy = {
  ...namesById,
} satisfies Record<number, string>;

type IdsCopy = keyof typeof namesByIdCopy;
//   ^? type IdsCopy = "1" | "2" | "3" | "4"

🙁 Actual behavior

IdsCopy has converted all of the keys to string literal union instead of a number literal union when using keyof typeof, even despite the fact that we've used satisfies Record<number, string> on the namesByIdCopy object.

🙂 Expected behavior

type IdsCopy = keyof typeof namesByIdCopy;
//   ^? type IdsCopy = "1" | "2" | "3" | "4"

should instead be typed as:

type IdsCopy = keyof typeof namesByIdCopy;
//   ^? type IdsCopy = 1 | 2 | 3 | 4

Additional information about the issue

The type inference seems to work as expected (i.e. numeric literal union) if as const is used on both the original object and the copy object, or if as const isn't used on the original object. It's only when spreading the object with anas const and inferring the keys using keyof typeof that they get inferred incorrectly.

コントリビュヌタヌガむド