Skip to content

Poor type inference for reduce #25454

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
ghost opened this issue Jul 5, 2018 · 5 comments
Open

Poor type inference for reduce #25454

ghost opened this issue Jul 5, 2018 · 5 comments
Labels
Domain: lib.d.ts The issue relates to the different libraries shipped with TypeScript Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript

Comments

@ghost
Copy link

ghost commented Jul 5, 2018

TypeScript Version: 3.0.0-dev.20180705

Code

function toStrings(arr: ReadonlyArray<object>): string[] {
	return arr.reduce((acc, obj) => {
		acc.push(obj.toString());
		return acc;
	}, [] as string[]);
}

Expected behavior:

No error.

Actual behavior:

src/a.ts:2:2 - error TS2322: Type 'object' is not assignable to type 'string[]'.
  Property 'length' is missing in type '{}'.

2  return arr.reduce((acc, obj) => {
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3  	acc.push(obj.toString());
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~
4  	return acc;
  ~~~~~~~~~~~~~
5  }, [] as string[]);
  ~~~~~~~~~~~~~~~~~~~~

src/a.ts:3:7 - error TS2339: Property 'push' does not exist on type 'object'.

3  	acc.push(obj.toString());

No error if arr is ReadonlyArray<number> or some other non-object type.
No error if I explicitly specify arr.reduce<string[]>.
No error if I remove the first two overloads to reduce, which are non-generic.

@ghost ghost added the Bug A bug in TypeScript label Jul 5, 2018
@ghost ghost added the Domain: lib.d.ts The issue relates to the different libraries shipped with TypeScript label Jul 5, 2018
@mhegazy mhegazy added Suggestion An idea for TypeScript Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. and removed Bug A bug in TypeScript labels Jul 23, 2018
@willyboy
Copy link

willyboy commented Mar 28, 2021

I think this goes here:

const things: Things[] = [{num:1}, {num:5}, {num: 2}];
this.things.slice(0, index).reduce((prevVal, curVal): number => {
      return prevVal.num + curVal.num;
    });

Error:
Argument of type '(prevVal: Things, curVal: Things) => number' is not assignable to parameter of type '(previousValue: Things, currentValue: Things, currentIndex: number, array: Things[]) => Things'.

Expected result is no error. We should be allowed to reduce an object to a single value that isn't the same object without using an initializer.

@lolmaus
Copy link

lolmaus commented Mar 28, 2021

@willyboy It's indicating a bug in your code.

You're not passing an intial value into .reduce(), so JavaScript expects both prevVal and curVal to be Things. But you're returning a number from the callback, which goes into prevVal.

TypeScript says that you have => number but it should be => Things. This is a legit, helpful error message.

Check out this snippet for comparison.

@russoedu
Copy link

russoedu commented Jun 8, 2022

I can add something to this.

I have an array with zeroes and ones created from a comparison (the example I'm posting here is a stupid version of it, just so the array type is (0 | 1)[]).

The reduce result is a positive number, but TS infers it will be 0 | 1.

const arr = [0, 1, 0, 0, 1, 1, 1, 1, 1, 1].map(v => v === 0 ? 0 : 1)
const sum = arr.reduce((p, c) => p + c, 0)

image

@Vulcagon
Copy link

Vulcagon commented Mar 22, 2025

I have a similar issue:

const recordArray: Record<string, any>[] = [
    { 'a': 1, 'b': 'B', 'c': [1, 2, 3] },
    { 'd': 4, 'e': 'E', 'f': [4, 5, 6] },
    { 'g': 7, 'h': 'H', 'i': [7, 8, 9] }
];

const reducedArray = recordArray.reduce(
    (map, record) => map,
    new Map<string, string>()
);

In this code reducedArray and the map parameter inside the reduce function are being inferred of type Record<string, any> instead of Map<string, string>. This also happens if the accumulator is an array or a Set and probably with many other types as well, but it works with simple types like string or number.

If recordArray is a Record<K, T> where T isn't any (even if it's unknown) the reduce seems to correctly infer its return type and the type of the accumulator.

The example above is a pretty stupid example but I think it shows the issue pretty well. My real code looks more like the following:

const reducedArray = recordArray.reduce(
    (map, record) => condition
        ? map.set(...)
        : map,
    new Map<...>()
);

Edit: The example below is actually a simple and useful example. It converts a Record<string, any>[] into a Map<number, any>:

const record: Record<string, any>[] = ...

const map = record.reduce(
    (acc, item, index) => acc.set(index, item.property),
    new Map<number, any>()
);

In this example the expected types for map and acc is Map<number, any> but they are inferred as Record<string, any> instead.

Again the interesting part is that it seems to work as long as T isn't any in Record<K, T> and you can argue that the fix is to don't use any but still, it's a bug

@lolmaus
Copy link

lolmaus commented Mar 24, 2025

@Vulcagon You can work around this problem by typing the accumulator in the callback:

const reducedArray = recordArray.reduce(
    (map: Map<string, string>, record) => map,
    new Map<string, string>()
);

But I agree that this should be considered a bug and fixed! When an initial value is passed into reduce, the accumulator in the callback (and thus the return type of reduce) should not be inferred from the source array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Domain: lib.d.ts The issue relates to the different libraries shipped with TypeScript Needs Proposal This issue needs a plan that clarifies the finer details of how it could be implemented. Suggestion An idea for TypeScript
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants