Skip to content

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.

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.

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.

@ahejlsberg ahejlsberg merged commit fde9c7f into master Mar 21, 2020
@ahejlsberg ahejlsberg deleted the fix36870 branch March 21, 2020 00:09
@microsoft microsoft locked as resolved and limited conversation to collaborators Oct 21, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

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

3 participants