TypeScript icon indicating copy to clipboard operation
TypeScript copied to clipboard

Primitive type narrowing doesn't respect re-assignment in function body

Open zachkirsch opened this issue 3 years ago • 1 comments

Bug Report

🔎 Search Terms

narrowing inside function

🕗 Version & Regression Information

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

⏯ Playground Link

Playground link with relevant code

💻 Code

let myBool = false; // on hover, myBool is typed as boolean

myBool // on hover, myBool is now typed as false

// change myBool from false to true
runCode(() => {
    myBool = true;
})

myBool // on hover, myBool is still typed as false

console.log(myBool) // correctly prints true

function runCode(run: () => void) {
    run();
}

🙁 Actual behavior

myBool is a boolean and declared with let. It is allowed to be changed to from false to true, and indeed I do! But TypeScript doesn't realize that I've changed it, so it narrows the type (on hover) to false even after I've changed it.

🙂 Expected behavior

Either: (1) TS shouldn't narrow the type to false at all, or (2) TS should realize that the value may have changed on the runCode(...) line, and therefore not restrict the type to false after that function call.

zachkirsch avatar Aug 09 '22 17:08 zachkirsch

Duplicate of #9998.

MartinJohns avatar Aug 09 '22 17:08 MartinJohns

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

typescript-bot avatar Aug 12 '22 18:08 typescript-bot