Skip to content

fix(lib): reorder Array#reduce/reduceRight overloads so generic <U> variant is tried first (#7014)#63440

Open
creazyfrog wants to merge 1 commit intomicrosoft:mainfrom
creazyfrog:fix/reduce-overload-order
Open

fix(lib): reorder Array#reduce/reduceRight overloads so generic <U> variant is tried first (#7014)#63440
creazyfrog wants to merge 1 commit intomicrosoft:mainfrom
creazyfrog:fix/reduce-overload-order

Conversation

@creazyfrog
Copy link
Copy Markdown

Fixes #7014

Problem

TypeScript resolves overloads by picking the first matching one. In src/lib/es5.d.ts, the reduce(callbackfn, initialValue: T): T overload was listed before the reduce<U>(callbackfn, initialValue: U): U overload. This caused TypeScript to infer T[] (the less-specific type) instead of a user-provided U type in cases like:

const result = [1, 2, 3].reduce((acc, x) => { acc.push(x); return acc; }, []);
//    ^^^^^^ was: number[][]  should be: number[]

Fix

Move the generic <U> overload above the T-with-initialValue overload for all four affected groups:

  • ReadonlyArray.reduce
  • ReadonlyArray.reduceRight
  • Array.reduce
  • Array.reduceRight

No new overloads added, no signatures changed — only the declaration order.

Verification

const nums = [1, 2, 3];
const result = nums.reduce<string[]>((acc, x) => [...acc, String(x)], []);
// result: string[]  ✓

…ariant is tried first

Fixes microsoft#7014. When TypeScript resolves overloads it picks the first matching one.
The `reduce(callbackfn, initialValue: T): T` overload was listed before
`reduce<U>(callbackfn, initialValue: U): U`, so `arr.reduce((acc, x) => ..., [])` inferred
`T[]` instead of the expected `U`. Moving the generic `<U>` overload above the `T`-with-initialValue
overload makes TypeScript try the more-specific version first. Applied to all four groups:
ReadonlyArray.reduce, ReadonlyArray.reduceRight, Array.reduce, Array.reduceRight.

Signed-off-by: creazyfrog <rohitcse.gec@gmail.com>
@github-project-automation github-project-automation Bot moved this to Not started in PR Backlog Apr 26, 2026
@typescript-bot typescript-bot added the For Backlog Bug PRs that fix a backlog bug label Apr 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

For Backlog Bug PRs that fix a backlog bug

Projects

Status: Not started

Development

Successfully merging this pull request may close these issues.

Consider re-ordering Array#reduce overloads in lib.d.ts

2 participants