microsoft / microsoft/TypeScript

Generic type gets widened in an unexpected way

Open
#52,249 7 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Domain: Mapped Types Help Wanted
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

🔎 Search Terms

widen

🕗 Version & Regression Information

4.9.4

⏯ Playground Link

Playground link with relevant code

💻 Code
enum One {
  A = 'a',
  B = 'b',
  C = 'c'
}

const isOneSomethingMap = {
  [One.A]: true,
  [One.B]: false,
  [One.C]: true
} as const satisfies Record<One, boolean>;

type BooleanMapToUnion<T extends Record<string, boolean>> = {
  [P in keyof T]: T[P] extends true ? P : never;
}[keyof T];

type SomethingOne = BooleanMapToUnion<typeof isOneSomethingMap>;

const a = <T>(value: T) => value;
const b = <T>(fn: (value: T) => T, v: T): T => fn(v);

const v: SomethingOne = One.A as SomethingOne;
const v2: One.A | One.C = One.A as One.A | One.C;

const r1 = b(a, v); // One and not SomethingOne - not expected
const r2 = a(v); // SomethingOne as expected
const r3 = b(a, v2); // Union as expected

const r4 = b(a, One.A as One.A | One.C); // Works
const r5 = b(a, One.A as SomethingOne); // Still doesn't work...
🙁 Actual behavior

The type gets widened when using BooleanMapToUnion... I guess it is the culprit.

🙂 Expected behavior

Both union and using BooleanMapToUnion should work equally.

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 reproduction and compare the inferred types of r1 through r5. Investigate how generic inference handles SomethingOne from BooleanMapToUnion versus the explicit union, then verify that the expected SomethingOne type is preserved for r1 and r5 without changing the behavior of the other examples.

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
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.