microsoft / microsoft/TypeScript

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

Open
#59,102 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Domain: check: Type Inference Help Wanted Possible Improvement
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

🔎 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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground and compare the inferred Ids and IdsCopy types in the provided reproduction. Trace how spreading an as const object affects keyof typeof and the satisfies Record<number, string> constraint. Done means the copied object's keys retain the numeric literal union shown in the expected behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.