Skip to content

Types for functions like Array.prototype.reduce or RxJS's "scan" seem impossible #46438

@benlesh

Description

@benlesh

Bug Report

I searched, and couldn't find a related issue (but I find it very unlikely one doesn't exist). It seems like there should be something labeled "Design Limitation" or the like?

The basic problem is if you're using a standard "reducer" callback pattern with a seed that is different from what your reducer returns the returned type is incorrect.

// The type of result is `number`, but should be `string`.
const result = [1, 2, 3].reduce((acc, value) => {
//                              ~~~~~~~~~~~~~~~~~
//                                 ^-- Error Here: "No overload matches this call"
    if (acc === null) {
        return '' + value;
    } else {
        return acc + ', ' + value;
    }
}, null);

console.log(result); // "1, 2, 3"
console.log(typeof result); // "string"

🔎 Search Terms

  • is:issue is:open array reduce
  • is:issue is:open reduce callback
  • is:issue is:open reduce "No overload matches this call"
  • is:issue is:open reduce label:"Design Limitation"

🕗 Version & Regression Information

Any version of TS, to TMK. Specifically tested in 4.2 and 4.4.4

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries as best I could. There's apparently a LOT of them. I didn't see anything related.

⏯ Playground Link

An example in the playground

💻 Code

// The type of result is `number`, but should be `string`.

const result = [1, 2, 3].reduce((acc, value) => {
//                              ~~~~~~~~~~~~~~~~~
//                                 ^-- Error Here: "No overload matches this call"
    if (acc === null) {
        return '' + value;
    } else {
        return acc + ', ' + value;
    }
}, null);

console.log(result); // "1, 2, 3"
console.log(typeof result); // "string"

🙁 Actual behavior

A type error, even though the compiled JavaScript is valid.

🙂 Expected behavior

No type error, result should be a type string, not number.

Related:

ReactiveX/rxjs#6649

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs 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