Skip to content

Assignment "resets" already narrowed type #60521

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 · 1 comment
Closed

Assignment "resets" already narrowed type #60521

hanwenguo opened this issue Nov 16, 2024 · 1 comment

Comments

@hanwenguo
Copy link

🔎 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/GYVwdgxgLglg9mABAdzgJwNYGcAUAPALkXAzDmTAEoiso0YwBzRAbwChFEZhEcoBPAA4BTODzyIAvNMQAiWvSazKrDp0QSA1JLkLZAbjWc0wqCDRI8+xAHobiAIIQIwwVGEATIgHI83rliIYACGaGjknohQcIjeCgyM3moAvojCADZYwqrqiCZmFnIGKWzJbGygkLAIiFgAFnAg6R4OmXAA6ugYAEIgUAAicMJYAHJwUPhEJGQU1LV0CTlcPHxCouJSMvILSirsuRI6WnJ1GelwBrb2vv4MeXWBMIFxO4kANLF+XEjpDwGx03IYCSuXy5ks1jsiAAKmtEABRMLoHxfJ6IAD6JiyUHRURi3kBFBBiFSGSyS2MpnBRUMnDKySAA

💻 Code

function works(x: unknown): string {
  if (typeof x === "string") {
    x += "str";
    return x; // Accepted: 'x' is narrowed to 'string'
  } else {
    return "";
  }
}

function shouldAlsoWorkButDoesNot(x: unknown): string {
  if (typeof x === "string") {
    x = x + "hello"; // 'x' in rhs is 'string', 'x' in lhs is 'unknown'
    return x; // Type Error: 'x' is _reset_ to 'unknown'
  } else {
    return "";
  }
}

🙁 Actual behavior

There is two problems:

  • as in shouldAlsoWorkButDoesNot, after the type of x is already narrowed to string, evaluating x = x + "hello" somehow "resets" the type of x to unknown.
  • the behavior of += and x = x + ... is inconsistent here.

🙂 Expected behavior

x = x + ... follow the behave of +=, which is correct, in the above code example.

Additional information about the issue

Concerning inconsistency between += and x = x + ..., also see #60520.

@jcalz
Copy link
Contributor

jcalz commented Nov 16, 2024

Duplicate of #27706

@hanwenguo hanwenguo closed this as not planned Won't fix, can't repro, duplicate, stale Nov 19, 2024
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