You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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)
functionworks(param: string|number): string{param=param+"a";returnparam;// Accepted: 'param' is narrowed to 'string'}functionshouldAlsoWorkButDoesNot(param: string|number): string{param+="a";returnparam;// 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.
🔎 Search Terms
"assignment operator" "type narrowing"
🕗 Version & Regression Information
⏯ Playground Link
https://www.typescriptlang.org/play/?ts=5.8.0-dev.20241116#code/GYVwdgxgLglg9mABAdzgJwNYGcAUAHAQzQIFsAuRLKNGMAc0QB9EwQSAjAUzQEoKqa9RAG8AUIkSFiJRAF5JRUogDUiAEQE1AbnGI0nKCDRIppLYgD0FxAEEIETniicAJhQDkpku8QwsLIjQ4ZFdEKDhEdwFaOndRAF9RUVBIWARKAAs4EAAbFxscrDgAdXQMACEQKAAROE4sADk4KHxFckpqGKYWNi5efk6hMQkvFXkNbV19Q2MFaXMrRAAVAE88TkQAUTQgtA8vHz9EAH0wZuOAneDQ8Mjo+jj4oA
💻 Code
🙁 Actual behavior
Compound assignments (
+=
) and their expanded equivalents (x = x + ...
) behave differently:param = param + "a"
correctly narrows butparam += "a"
does not.🙂 Expected behavior
+=
should behave equivalently tox = 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
+=
andx = x + ...
is #60521.The text was updated successfully, but these errors were encountered: