Narrowing from truthy unknown to object#37507
Merged
ahejlsberg merged 4 commits intomasterfrom Mar 21, 2020
Merged
Conversation
src/compiler/checker.ts
Outdated
| return type; | ||
| } | ||
| if (assumeTrue && type.flags & TypeFlags.Unknown && literal.text === "object") { | ||
| // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. |
Member
There was a problem hiding this comment.
Would be nice to note here that you don't need to check both directions because the typeof x === "object" && x is narrowed as two separate steps. I don't think that would be obvious to a casual reader.
src/compiler/checker.ts
Outdated
| return false; | ||
| } | ||
|
|
||
| function containsTruthyCheck(source: Node, target: Node) { |
Member
There was a problem hiding this comment.
A comment here that this specifically deals the binary operator precedence. would also be useful. The implementation looks good here, but this function is named something much more general than it actually is and that's going to be confusing in the future.
DanielRosenwasser
approved these changes
Mar 20, 2020
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
With this PR, given a variable
xof typeunknown, the patternx && typeof x === 'object'narrowsxtoobject. Previously we'd narrow toobject | nullbecause a truthiness check applied tounknownis stillunknown(andunknownincludesnull).Note that this is a targeted fix for a relatively common pattern. In an ideal world we'd be able to accurately represent types that are known to be truthy, but we currently don't have that ability.
Fixes #36870.