Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
svr93 opened this issue Oct 8, 2019 · 1 comment
Open

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

svr93 opened this issue Oct 8, 2019 · 1 comment
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript

Comments

@svr93
Copy link

svr93 commented Oct 8, 2019

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
@RyanCavanaugh RyanCavanaugh added In Discussion Not yet reached consensus Suggestion An idea for TypeScript labels Oct 30, 2019
@RyanCavanaugh
Copy link
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
Labels
In Discussion Not yet reached consensus Suggestion An idea for TypeScript
Projects
None yet
Development

No branches or pull requests

2 participants