Skip to content

[Array.prototype.reduce] TS infers accumulator type as any[] #33886

Open
@svr93

Description

@svr93

TypeScript Version: 3.7-Beta, "noImplicitAny" compiler mode

Search Terms:
Array.prototype.reduce, reduce type inference, reduce implicit any

Code

const result = [1].reduce((acc, item) => {
    acc.push(item)
    return acc
}, [])

result[0].toLowerCase()

Expected behavior:

  1. result implicitly has type any[] -> compiler error ("noImplicitAny")
    or
  2. result has type unknown[] -> compiler error

Actual behavior:
result has type any[], no errors

Playground Link: http://www.typescriptlang.org/play/?strictNullChecks=false&strictPropertyInitialization=false&ts=3.7-Beta&ssl=6&ssc=24&pln=1&pc=1#code/MYewdgzgLgBATgUwgVwDawLwwNoEYC6AdIgCbLAIAUlAhsMADQwCWUCAtgJQwYB8MAbwBQMUTDrBCAB2QQAFpVYdOIsYijI4YcfSEBfJtnwqhiFOmwAGIlBAAZEAHcEcAMI0IVTkA

Related Issues: #25454, #29604

P.S. It seems reasonable to align behavior with other empty array cases, e.g.:

let x = {
    array: [] // Object literal's property 'array' implicitly has an 'any[]' type
}

let x = []
x[0].toLowerCase() // Variable 'x' implicitly has type 'any[]' in some locations where its type cannot be determined

Activity

RyanCavanaugh

RyanCavanaugh commented on Oct 30, 2019

@RyanCavanaugh
Member

We should try to write a new definition of reduce that produces the desired behavior in all cases

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

    In DiscussionNot yet reached consensusSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @svr93@RyanCavanaugh

        Issue actions

          [Array.prototype.reduce] TS infers accumulator type as any[] · Issue #33886 · microsoft/TypeScript