Skip to content

Variable modified in loop supposedly "referenced directly or indirectly in its own initializer" #43047

Closed as not planned
@jtbandes

Description

@jtbandes

Bug Report

The following code produces this error on two lines:

'currentFoo' implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer.(7022)

This is a reduced repro case from a real code snippet. It seems like maybe the error is arising when the compiler tries to refine the types of these variables by looking at assignment expressions. But the result is unintuitive and unhelpful.

Expected behavior:

At worst, the compiler should just give currentFoo the same type as the declaration of foo, and this would be better than the current behavior.

TS playground

  let foo: {value:number} | undefined;

  function bar() {
    foo = {value: 1};

    while (true) {
      const currentFoo = foo;  // error here
      if (currentFoo) {
        const currentValue = currentFoo.value;  // error here
        foo = {value: currentValue+1};
        if (currentValue > 1) break;
      }
    } 
  }

🔎 Search Terms

implicitly has type 'any' because it does not have a type annotation and is referenced directly or indirectly in its own initializer

Possibly related issues: #16892, #22390, #35546

🕗 Version & Regression Information

  • This is the behavior in every version I tried

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions