TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Resolving type incorrectly when loop is involved

Open MathMan05 opened this issue 1 month ago • 2 comments

🔎 Search Terms

assignment narrowing assignment narrowing union

🕗 Version & Regression Information

Version 6.0.0-dev and 5.9.3

⏯ Playground Link

https://www.typescriptlang.org/play/#code/DYUwLgBMCGDOYC4IFcB2ATEAzAlqk6EAPhPAE54DmEAvChtngQFADGA9qvBAG7TDIQtCAHIARjAAWI5syzsyEABQBuFQEoIAb2YQIHLpHwAPSHRjxdEHFmUnIAQhp0+AkJq0BfKxbO9+gsyeQA

💻 Code

let last: undefined | string = undefined
const value = 'blah'

for (;;) {
  const next = last
  if (next !== value) {}
  last = value
}

🙁 Actual behavior

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

🙂 Expected behavior

No error

Additional information about the issue

Might be related to: https://github.com/microsoft/TypeScript/issues/33191 I ran into the issue initially and @mkantor created the minified example that produces the same error.

MathMan05 avatar Dec 09 '25 20:12 MathMan05

also to note, the useless if statement if removed makes things work again

MathMan05 avatar Dec 09 '25 20:12 MathMan05

See https://github.com/Microsoft/TypeScript/wiki/FAQ#circularity-errors-may-occur-in-the-presence-of-circularities

The if is relevant here because (in the case where it's not just blank, which is degenerate), there might be an exit point (return, continue, never-returning function, etc) which could change what kind of values can get into last

RyanCavanaugh avatar Dec 09 '25 21:12 RyanCavanaugh

This issue has been marked as "Not a Defect" and has seen no recent activity. It has been automatically closed for house-keeping purposes.

typescript-bot avatar Dec 12 '25 01:12 typescript-bot