Skip to content

Conversation

@taronsung
Copy link

Summary

Reorder the overload declarations for reduce and reduceRight in both ReadonlyArray<T> and Array<T> interfaces so the generic <U> overload (with initialValue: U) is checked before the same-type overload (with initialValue: T).

Problem

When calling reduce with an initial value of a different type than the array elements, TypeScript incorrectly infers the return type. This is because TypeScript checks overloads in declaration order, and the initialValue: T overload matches before the generic <U> overload gets a chance.

Example from #7014:

type UnaryFunction = (arg1: any) => any;
type BinaryFunction = (arg1: any, arg2: any) => any;

let binaryFuncs: BinaryFunction[] = [];
let unaryFunc: UnaryFunction = arg1 => {};
let reduced = binaryFuncs.reduce((prev, next) => prev, unaryFunc);

// BEFORE: Error - Type 'BinaryFunction' is not assignable to type 'UnaryFunction'
// AFTER: Works correctly - reduced is inferred as UnaryFunction
let f: UnaryFunction = reduced;

Solution

Swap the order of the two overloads that take an initialValue parameter:

  • Before: reduce(cb, initialValue: T) then reduce<U>(cb, initialValue: U)
  • After: reduce<U>(cb, initialValue: U) then reduce(cb, initialValue: T)

The same change is applied to both reduce and reduceRight in both ReadonlyArray<T> and Array<T>.

Fixes #7014

Reorder the overload declarations for reduce and reduceRight in both
ReadonlyArray<T> and Array<T> interfaces so the generic <U> overload
(with initialValue: U) is checked before the same-type overload
(with initialValue: T).

This fixes incorrect type inference when calling reduce/reduceRight
with an initial value of a different type than the array elements.

Fixes microsoft#7014
@github-project-automation github-project-automation bot moved this to Not started in PR Backlog Jan 29, 2026
@typescript-bot typescript-bot added the For Backlog Bug PRs that fix a backlog bug label Jan 29, 2026
@taronsung
Copy link
Author

@microsoft-github-policy-service agree

The overload order change affects the displayed type signature and
improves type inference in some cases (e.g., anyInferenceAnonymousFunctions
now correctly infers any[] instead of any when reduce is called with []
as the initial value).
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