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

Narrowing one value based on another is not preserved across repeat conditionals #60916

Closed
JoshuaKGoldberg opened this issue Jan 5, 2025 · 1 comment
Labels
Duplicate An existing issue was already created

Comments

@JoshuaKGoldberg
Copy link
Contributor

JoshuaKGoldberg commented Jan 5, 2025

πŸ”Ž Search Terms

narrow union two values narrowing if condition

πŸ•— Version & Regression Information

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

⏯ Playground Link

https://www.typescriptlang.org/play/?#code/CYUwxgNghgTiAEAzArgOzAFwJYHtXwHMQMBlDGLVAgeRgFVVRFKRgAKASgC54BncygXgAfeGiYtgAbgBQM0JFgIU6bHnhwwILADcQAMRg4Atm0RHjPfhSrd4OnFmlyQADwAOOGBiRpMufAwQfjZjHFAeAHIoSJF4SIAjSI54AG8ZeHgwPH54VFgjAHcoBIgEAF5CYjIbGnpGEGZUVk5ZDPgsRHhQ8IryyoAiKAH4ADJR+ABCfJgikrKU9MzMuAxkGFRZTIBfOUyAen34ADpTvY6untB4fsHhxfaV8G09QxM2GbnSkA4t+F3tkA

πŸ’» Code

declare function getStringOrUndefined(): string | undefined;

declare function receiveFrom(from: string): void;

export function test(mode: 'a' | 'b') {
  const narrowable = getStringOrUndefined();

  if (mode === "a" && !narrowable) {
    return;
  }

  // ...

  if (mode === "a") {
    receiveFrom(narrowable);
    //          ~~~~~~~~~~
    // Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
    // Type 'undefined' is not assignable to type 'string'.
  }
}

πŸ™ Actual behavior

narrowable is type string | undefined inside the second if.

πŸ™‚ Expected behavior

We know that if mode === "a" then narrowable must be truthy. Otherwise the early return; would have been hit.

Additional information about the issue

I have a hunch I've seen this before, but searched through issues a bunch and couldn't find anything...

This is a simplified example from real-world code. The // ... contains some logic that must happen regardless of mode.

@MartinJohns
Copy link
Contributor

Duplicate of #52822.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Jan 6, 2025
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

3 participants