Typescript: Wrong type narrowing for variable updated in inner scope

Created on 19 Sep 2019  ·  2Comments  ·  Source: microsoft/TypeScript


TypeScript Version: 3.7.0-dev.20190919


Search Terms:
variable, type inference, narrowed, lost
Code

let a: boolean = false;
const modifyA = (): void => {
  a = true;
};
modifyA();
if (a) { // a is inferred as false
  console.log('a is true');
}

I'm not sure if it can lead to something bad inside typescript, but it creates problem for typescript-eslint (check related issue).

Expected behavior:
a is inferred as boolean

Actual behavior:
a is inferred as false

Playground Link:
https://www.typescriptlang.org/play/#code/DYUwLgBAhgXBBGB7RooDsIF4IDMrAGcQBuAKAGNE0DIBbRAEwEscBPAQSwgAoBKOAG6ImDLAD4IAb1IRoXMACcAriVIBfMvWZt2fMix5ReUiAHpTcpgQhM0OEAoUhRUa3kIgZEStRQgAdMCIAObcAORQEADurhBaLEzOYbxkaqRAA

Related Issues:
https://github.com/typescript-eslint/typescript-eslint/issues/989

Most helpful comment

All 2 comments

Sure, sorry for duplicate

Was this page helpful?
0 / 5 - 0 ratings