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

Reflect control flow effects of optional chains in equality checks #33821

Merged
merged 8 commits into from
Oct 6, 2019

Conversation

ahejlsberg
Copy link
Member

@ahejlsberg ahejlsberg commented Oct 4, 2019

With this PR we properly reflect control flow effects of optional chains in equality checks. Specifically, when compiling with --strictNullChecks,

  • in code guarded by o?.foo === value, where the type of value doesn't include undefined, we remove undefined and null from the type of o in the true branch, and
  • in code guarded by o?.foo == value, where the type of value doesn't include undefined or null, we remove undefined and null from the type of o in the true branch, and
  • in code guarded by o?.foo !== undefined, o?.foo != undefined or o?.foo != null we remove undefined and null from the type of o in the true branch, and
  • in code guarded by typeof o?.foo === "xxx" or typeof o?.foo == "xxx" we remove undefined and null from the type of o in the true branch, and
  • in code guarded by o?.foo instanceof xxx we remove undefined and null from the type of o in the true branch.

Some examples:

type Thing = { foo: number, bar(): number };

function foo(o: Thing | undefined, value: number) {
    if (o?.foo === value) {
        o.foo;  // Ok
    }
    if (o?.["foo"] === value) {
        o["foo"];  // Ok
    }
    if (o?.bar() === value) {
        o.bar;  // Ok
    }
    if (o?.foo !== undefined) {
        o.foo;  // Ok
    }
    if (o?.["foo"] !== undefined) {
        o["foo"];  // Ok
    }
    if (o?.bar() !== undefined) {
        o.bar;  // Ok
    }
}

Fixes #33806.

@ahejlsberg ahejlsberg requested a review from rbuckton October 4, 2019 23:27
@falsandtru
Copy link
Contributor

Does this support typeof o?.foo === 'number' and o?.bar instanceof Function? I couldn't find the tests for them.

@ahejlsberg
Copy link
Member Author

ahejlsberg commented Oct 5, 2019

With latest commits we only perform checks in --strictNullChecks mode. Also, latest commits add support for typeof and instanceof as well as the == and != operators.

@ahejlsberg ahejlsberg requested a review from rbuckton October 5, 2019 20:21
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.

CFA with optional chaining
3 participants