microsoft / microsoft/TypeScript

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

Open
#33,886 1 comment 11 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

In Discussion Suggestion
Dominant language
Go
Stars
111k
Forks
14.3k
Avg merge
2d 4h
Merged PRs (30d)
132

Description

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: https://github.com/microsoft/TypeScript/issues/25454, https://github.com/microsoft/TypeScript/issues/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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked TypeScript Playground reproduction under noImplicitAny and compare it with the related issues 25454 and 29604. The work is done when the empty-array accumulator is diagnosed or reported consistently with the other empty-array cases, producing the expected compiler error.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.