microsoft / microsoft/TypeScript

A series of nested loops, undefined and `in` checks results in incorrect implicit any

Open
#45,638 2 comments 1 reaction 1 assignee View on GitHub

@elibarzilay is already working on this.

Since Sep 2, 2021.

Needs Investigation Rescheduled
Dominant language
Go
Stars
111k
Forks
14.4k
Avg merge
1d 19h
Merged PRs (30d)
117

Description

Bug Report

A series of nested loops, undefined and in checks results in incorrect implicit any.

I don't know what is really causing this. It seems this might be a weird edge case where type inference fails?

🔎 Search Terms

noImplicitAny, inference

🕗 Version & Regression Information

This changed between versions 4.3.5 and 4.4.2

⏯ Playground Link

Playground link with relevant code

💻 Code
interface MyObj { id?: string; }
declare var objects: MyObj[]|undefined;

if (objects) {
  for (const _ of []) {
    const map: {[key:string]: string|undefined} = {};

    for (const obj of objects) {
      //       ~~~ 'obj' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)
      const id = obj.id!;
      //    ~~ 'id' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)
      if (id in map) {
        console.log(id);
      }
    }
  }
}
🙁 Actual behavior

In version 4.4.2 the above code fails to compile with the 2 errors.

Any of the following changes cause it compile without errors:

  • Remove |undefined from the objects type.
  • Remove the outer for (const _ of []) loop
  • Remove if (id in map)
  • Add a type annotation to the id variable: const id: string = obj.id!
🙂 Expected behavior

The code should compile without errors as it did in version 4.3.5.

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.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.