Skip to content

Incorrect return type for Array.prototype.reduce() #21061

@kwpeters

Description

@kwpeters

The TypeScript compiler thinks the type of the instances.reduce() call below is C1 | string. I believe the return type should be string.

Code

class C1
{
}

type ItemType = C1 | string;

const instances: Array<ItemType> = [new C1(), "foo", new C1(), "bar"];

// The following line produces
// error TS2322 Type 'ItemType' is not assignable to type 'string'.
// Type 'C1' is not assignable to type 'string'.
const result: string = instances.reduce(
    (acc: string, curItem: ItemType): string => {
        if (curItem instanceof C1) {
            return acc + "C1";
        } else {
            return acc +curItem;
        }
    },
    ""
);

Expected behavior:
I would expect the above code to compile without errors. If I use the Lodash's version of reduce() (_.reduce()) it compiles successfully.

Actual behavior:
The assignment of the result variable results in "error TS2322 Type 'ItemType' is not assignable to type 'string'. Type 'C1' is not assignable to type 'string'." When evaluating the type of the instances.reduce() expression, it is C1 | string. I would expect it to be just string.

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions