Skip to content

Narrowing from truthy unknown to object #37507

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

Merged
merged 4 commits into from
Mar 21, 2020
Merged

Narrowing from truthy unknown to object #37507

merged 4 commits into from
Mar 21, 2020

Conversation

ahejlsberg
Copy link
Member

With this PR, given a variable x of type unknown, the pattern x && typeof x === 'object' narrows x to object. Previously we'd narrow to object | null because a truthiness check applied to unknown is still unknown (and unknown includes null).

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.

@@ -20343,15 +20349,22 @@ namespace ts {
if (type.flags & TypeFlags.Any && literal.text === "function") {
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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@@ -18947,6 +18947,12 @@ namespace ts {
return false;
}

function containsTruthyCheck(source: Node, target: Node) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

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

Successfully merging this pull request may close these issues.

Truthy check loses effect based on position in "&&" chain
2 participants