Skip to content

Poor type inference for reduce #25454

Open

Description

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.

Activity

  1. ghost added
    BugA bug in TypeScript
    on Jul 5, 2018
  2. ghost added
    Domain: lib.d.tsThe issue relates to the different libraries shipped with TypeScript
    on Jul 5, 2018
  3. added
    SuggestionAn idea for TypeScript
    Needs ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.
    and removed
    BugA bug in TypeScript
    on Jul 23, 2018
  4. willyboy commented on Mar 28, 2021

    @willyboy

    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.

  5. lolmaus commented on Mar 28, 2021

    @lolmaus

    William Neely (@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.

  6. russoedu commented on Jun 8, 2022

    @russoedu

    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

  7. Vulcagon commented on Mar 22, 2025

    @Vulcagon

    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

  8. lolmaus commented on Mar 24, 2025

    @lolmaus

    Vulcagon (@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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Domain: lib.d.tsThe issue relates to the different libraries shipped with TypeScriptNeeds ProposalThis issue needs a plan that clarifies the finer details of how it could be implemented.SuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions