Skip to content

TypeScript 2.5 not inferring return type of reduce #19823

Closed
@aboyton

Description

@aboyton

TypeScript Version: 2.7.0-dev.201xxxxx

Code
This is a (reasonably) minimal example of the code I'm compiling. My actual function is filtering entries before reconstructing the object.

 export function foo<V>(object: { [key: string]: V }): { [key: string]: V } {
  const entries = Object.entries(object);
  const rv = entries.reduce((obj: { [key: string]: V }, [key, value]) => {
    obj[key] = value;
    return obj;
  }, {});
  return rv;
}

Note that the above code requires some options to use Object.entries and so you can reproduce the same error with the following code snippet if desired.

const entries: [string, V][] = []; // 
const rv = entries.reduce((obj: { [key: string]: V }, [key, value]) => {
  obj[key] = value;
  return obj;
}, {});

Expected behavior:
In TypeScript 2.4.2 the constant rv is correctly inferred to be of type { [key: string]: V } but it does not seem to be in TypeScript 2.5.3.

Actual behavior:
rv is inferred to be of type {}.

It doesn't seem like the definition of reduce has changed between versions. VSCode is jumping to this signature of reduce.

reduce<U>(callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: T[]) => U, initialValue: U): U;

Obviously I can specify the return value of my function foo as I have and everything works, but previously I did not need to as it was correctly inferred.

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions