Skip to content

Narrowing from truthy unknown to object - #37507

Merged
Anders Hejlsberg (ahejlsberg) merged 4 commits into
masterfrom
fix36870
Mar 21, 2020
Merged

Narrowing from truthy unknown to object#37507
Anders Hejlsberg (ahejlsberg) merged 4 commits into
masterfrom
fix36870

Conversation

@ahejlsberg

Copy link
Copy Markdown
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.

Comment thread 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.

Copy link
Copy Markdown
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.

Comment thread src/compiler/checker.ts Outdated
return false;
}

function containsTruthyCheck(source: Node, target: Node) {

Copy link
Copy Markdown
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 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

2 participants