Skip to content

Inconsistent type narrowing behavior between compound assignment operators and their expanded equivalents #60520

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

Closed
hanwenguo opened this issue Nov 16, 2024 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@hanwenguo
Copy link

hanwenguo commented Nov 16, 2024

🔎 Search Terms

"assignment operator" "type narrowing"

🕗 Version & Regression Information

  • This is the behavior in every version in the Playground that I tried, and I reviewed the FAQ for entries about assignment operators and narrowing (there isn't any, though)

⏯ Playground Link

https://www.typescriptlang.org/play/?ts=5.8.0-dev.20241116#code/GYVwdgxgLglg9mABAdzgJwNYGcAUAHAQzQIFsAuRLKNGMAc0QB9EwQSAjAUzQEoKqa9RAG8AUIkSFiJRAF5JRUogDUiAEQE1AbnGI0nKCDRIppLYgD0FxAEEIETniicAJhQDkpku8QwsLIjQ4ZFdEKDhEdwFaOndRAF9RUVBIWARKAAs4EAAbFxscrDgAdXQMACEQKAAROE4sADk4KHxFckpqGKYWNi5efk6hMQkvFXkNbV19Q2MFaXMrRAAVAE88TkQAUTQgtA8vHz9EAH0wZuOAneDQ8Mjo+jj4oA

💻 Code

function works(param: string | number): string {
  param = param + "a";
  return param; // Accepted: 'param' is narrowed to 'string'
}

function shouldAlsoWorkButDoesNot(param: string | number): string {
  param += "a";
  return param; // Type Error: 'param' is _not_ narrowed to 'string'
}

🙁 Actual behavior

Compound assignments (+=) and their expanded equivalents (x = x + ...) behave differently: param = param + "a" correctly narrows but param += "a" does not.

🙂 Expected behavior

+= should behave equivalently to x = x + ... with respect to type narrowing.

Additional information about the issue

The code example is taken from here.

Another less relevant issue which also reveals the inconsistency between += and x = x + ... is #60521.

@jcalz
Copy link
Contributor

jcalz commented Nov 16, 2024

duplicate-ish of #9815 and/or #17204 and/or #44553? Also related to #47027 (as linked above).

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Dec 2, 2024
@typescript-bot
Copy link
Collaborator

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

@typescript-bot typescript-bot closed this as not planned Won't fix, can't repro, duplicate, stale Dec 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants