microsoft/TypeScript

type incorrectly narrowed because assignment of a different value in function not seen

Closed this issue ยท 2 comments

190n commented

๐Ÿ”Ž Search Terms

"incorrect narrowing," "control flow assignment"

๐Ÿ•— Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about incorrect narrowing

โฏ Playground Link

https://www.typescriptlang.org/play/?ts=6.0.0-dev.20251024#code/DYUwLgBAZg9jBcEDeEBGBDATogdgVwFtURMIBfCAHwn2GAgF4a86BuAKCjxwGMwBLGDgjoAzqP4BzHAAoAlMnYRocRsjRZEAVnIcy7AO4ALfqAgywmPCAVIlEflHOwYjBk1rBb95WInT5DmUKEGBREEVlZQA3GH4AExUYADoMTCDydn0gA

๐Ÿ’ป Code

let foo: { bar: number } | null = null;
function assign() {
  foo = { bar: 5 };
}
while (true) {
  if (foo === null) {
    assign();
  } else {
    void foo.bar;
  }
}

๐Ÿ™ Actual behavior

There is an error on the bar property lookup. foo has been narrowed to null because TypeScript thinks we never assign it to something other than null, and in the else branch it is narrowed to never because we've checked it is not null so there are no more types it could possibly be.

๐Ÿ™‚ Expected behavior

There should be no error. If TypeScript cannot prove that foo is never assigned a non-null value then it should not assume that.

Additional information about the issue

No response

jcalz commented

Yet another duplicate of #9998

190n commented

Ah sorry I didn't find that one, thanks.