Skip to content

Type narrowing doesn't work inside constant ternary operator #50393

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
Noa-Ivix opened this issue Aug 21, 2022 · 2 comments
Closed

Type narrowing doesn't work inside constant ternary operator #50393

Noa-Ivix opened this issue Aug 21, 2022 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@Noa-Ivix
Copy link

Bug Report

πŸ”Ž Search Terms

  • Ternary narrowing
  • Constant ternary
  • Constant ternary narrowing

πŸ•— Version & Regression Information

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

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

function works1(s: number | null) {
  return s !== null ? s.toString() : ""
}
function works2(s: number | null) {
  return true ? (
      s !== null ? s.toString() : ""
    ) : "";
}
function doesnt_works(s: number | null) {
  return false ? (
      s !== null ? s.toString() : ""
                // ^ Object is possibly 'null'
    ) : "";
}

πŸ™ Actual behavior

Function doesnt_work fails to compile because s is assumed to be number | null even though we just checked that s !== null.

πŸ™‚ Expected behavior

This should either compile successfully or maybe produce an error/warning about unreachable code.
The expression s !== null ? s.toString() : "" was correct when used on its own but became invalid once I placed it in a false branch of a ternary operator, for no apparent reason.

@fatcerberus
Copy link

See #26914

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 26, 2022
@typescript-bot
Copy link
Collaborator

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

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