Skip to content

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

Merged
Anders Hejlsberg (ahejlsberg) merged 8 commits into
masterfrom
fix33806
Oct 6, 2019
Merged

Anders Hejlsberg (ahejlsberg) merged 8 commits into
masterfrom
fix33806

Conversation

@ahejlsberg

@ahejlsberg Anders Hejlsberg (ahejlsberg) commented Oct 4, 2019 •

Copy link
Copy Markdown
Member

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.

Comment thread src/compiler/checker.ts Resolved
@falsandtru

Copy link
Copy Markdown
Contributor

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

@ahejlsberg

Anders Hejlsberg (ahejlsberg) commented Oct 5, 2019 •

Copy link
Copy Markdown
Member Author

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.

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.

CFA with optional chaining

3 participants