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

Type inference / type narrowing incorrect when using the Boolean() BooleanConstructor #38397

Closed
0xCLARITY opened this issue May 7, 2020 · 2 comments

Comments

@0xCLARITY
Copy link

0xCLARITY commented May 7, 2020

TypeScript Version: 3.8.3 + Nightly

Search Terms:
Inference
Boolean

Code

// This function correctly narrows the type of tag
// and gives us the correct return type
function validFunction(tag: number | undefined): number | false {
  return !!tag && tag
}

// This function allegedly returns `number | false | undefined`,
// and gives a TS error, even though that is obviously not true.
function invalidFunction(tag: number | undefined): number | false {
  return Boolean(tag) && tag
}

Expected behavior:
I expect using a Boolean() BooleanConstructor to narrow the type as effectively as the !! operator.

Actual behavior:
The Boolean constructor does not narrow the type correctly. I found this when attempting to refactor some code to follow the `no-implicit-coercion ESLint rule.

Playground Link:
https://www.typescriptlang.org/play/?ts=4.0.0-dev.20200506&ssl=3&ssc=2&pln=1&pc=1#code/GYVwdgxgLglg9mABDMA3AhgGxgEwGLjTxgAUU6A5gFyJggC2ARgKYBOiAPouDs8CsxwBKGnSZtOiYFgDOzRAG8AsAChEiVsyghWSAEJw4mZulLkKQxADIric6oC+q1aEiwEiDNnyF3ZyqIMLOxcPHwCwoHiIVKy8spqGlo6SACEqebWtvYqDkA

Related Issues:

Misc: If this does turn out to be a bug, I'm happy to write a PR to fix this given some guidance.

@MartinJohns
Copy link
Contributor

Duplicate of #16655. Search terms: boolean narrow

@0xCLARITY
Copy link
Author

Closing since it's a dupe of #16655.

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