Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript incorrectly narrows boolean type to true for variable updated within Map<...>.get(...)?.forEach(...) block. #60357

Closed
paulkim3151 opened this issue Oct 28, 2024 · 1 comment

Comments

@paulkim3151
Copy link

paulkim3151 commented Oct 28, 2024

πŸ”Ž Search Terms

"type narrowing", "map of set"

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried (including v5.6.3 and 5.7.0-beta in playground)

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.6.3#code/MYewdgzgLgBAtgQwA4HkBmBlAplAXDAWWQB5oAnASzAHMAaGbKUqSmgPjZgF4YwsB3QsgAUASgDcAKESpMOAHQQcwgEQBrLAE8V9PoMaqEK0RMmSANjhhoQIbjBYBXLFJnpG86svVbjAfnkbMgBRBGAAC2Exbk4Ab0kYa1t7NARzJSkAX1NJUEgQS3lzEGphGxBTIA

πŸ’» Code

const mapOfSet: Map<string, Set<string>> = new Map();
mapOfSet.set("key", new Set("a"));

let foo = true;
mapOfSet.get("key")?.forEach(() => {
  foo = false;
});

console.log(foo); 

πŸ™ Actual behavior

The foo variable is expected to be of type boolean because it may change to false within the .forEach(...) block. However, TypeScript incorrectly narrows foo's type to true, assuming it will not change.

πŸ™‚ Expected behavior

TypeScript should maintain the boolean type for the foo variable, as it can change to false inside the .forEach(...) block when the map's value is accessed and iterated over.

Additional information about the issue

No response

@MartinJohns
Copy link
Contributor

Duplicate of #9998.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants