microsoft/TypeScript

Variable assigned in closure narrowing to wrong type

bennetthardwick opened this issue · 5 comments

TypeScript Version: 3.333 -> 4.1.0

Search Terms:

  • function type interface
  • type narrowing callback
  • type narrowing captured closure
  • type incorrectly narrowing captured closure

Code

function doSomething(callback: () => void) {
  callback();
}

let result: 'foo' | 'bar' = 'bar';

doSomething(() => {
    result = 'foo';
})

// This should work, but fails because type is always "bar"
if (result === 'foo') {

}

Expected behavior:

It compiles.

Actual behavior:

Compiler error:

This condition will always return 'false' since the types '"foo"' and '"bar"' have no overlap.

Playground Link:

https://www.typescriptlang.org/play?ts=4.0.2#code/GYVwdgxgLglg9mABAEzgZTgWwKZQBYxgDmAFBAIYA2lARuRANYBciJAlIgLwB8iAbnBjIOAbwBQiRBWp1G7ANxiAvmLGVciAE7YAziEpQWAcmBw4RxAB9ERupoucbdo4rGoMOfIVLsuvcZKS2noGXDam5opKbKoA9LGIACoEOog6eHD6yIgA7nCaDIh42NoAhGIwwKzB+lBcnI4mZkaiqkpAA

Related Issues:

Possibly #9998?

Duplicate of #9998. It's literally the first example.

Duplicate of #9998. It's literally the first example.

Ahh yep. @MartinJohns is that the canonical issue for tracking this bug? It's got a "discussion" label and no progress seems to have been made.

is that the canonical issue for tracking this bug?

I'd say yes. Every other of the many many many many many many duplicates have been closed in favor of it already.

Thanks! Any word on whether this and the many many many many many many duplicates will get fixed?

Unlikely, due to the reasons explained in #9998.