microsoft / microsoft/TypeScript

Support "evolving any" with forEach / internal functions

Open
#35,132 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

TypeScript 2.1 introduced the notion of an "evolving" any type, a variable whose type is determined based on subsequent usage:

function square(xs: number[]) {
    const ys = [];
    for (const x of xs) {
        ys.push(x * x);
    }
    return ys;  // type is number[], hooray!
}

Unfortunately this is a bit brittle. If you ever introduce an internal function (say if you use forEach) then the inferred type is lost and you get a no implicit any error:

function square(xs: number[]) {
    const ys = [];  // Variable 'ys' implicitly has type 'any[]' in some locations
                    // where its type cannot be determined. (7034)
    xs.forEach(x => {
        ys.push(x * x);
    });
    return ys;  // Variable 'ys' implicitly has an 'any[]' type. (7005)
}

The two forms do the same thing, so it's somewhat surprising that the for-of version passes the type checker but the forEach version does not.

I find the "evolving any" construct to be incredibly useful, but I have to scrap it every time I introduce an arrow function. I'm proposing that it be extended to work for cases like this.

TypeScript 3.7.2
Playground link

Expected behavior:

I'd expect both versions to pass the type checker and infer the type of ys as number[].

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 Playground example and compare the for-of and forEach forms described in the issue. The change is complete when both forms pass the type checker and infer ys as number[] without implicit-any errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
compilers
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.