microsoft / microsoft/TypeScript

Order of ReadonlySet/ReadonlyMap in union causes differing key inference

Open
#52,313 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: check: Type Inference Has Repro Union Order Dependence
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

ReadonlyMap ReadonlySet key inference

🕗 Version & Regression Information
  • This is the behavior in every version I tried.
⏯ Playground Link

Playground Link

💻 Code
declare const map: Map<string, number>;


declare function forEachKey<K, T>(map: ReadonlySet<K> | ReadonlyMap<K, any>, callback: (key: K) => T | undefined): T | undefined;

forEachKey(map, (key) => {}) // Error passing "map", key type is wrong (number??)

forEachKey<string, void>(map, (key) => {}) // OK; no error, key type is string


// Now, flip the union order in the parameter's type.
declare function forEachKey2<K, T>(map: ReadonlyMap<K, any> | ReadonlySet<K>, callback: (key: K) => T | undefined): T | undefined;

forEachKey2(map, (key) => {}) // Okay?

forEachKey2<string, void>(map, (key) => {}) // Still okay.
🙁 Actual behavior

The order of the union appears to matter, breaking inference and erroring on valid code. Swapping the union order allows the code to compile.

🙂 Expected behavior

All of this should compile; the union ordering should not matter.

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 repro and compare inference for the two union orders in forEachKey and forEachKey2. Trace the generic union inference behavior in the compiler, then add a regression test showing that both declarations infer string and that all four calls compile regardless of union order.

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
Quiet
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.