Skip to content

Condition aliasing doesn't capture optional chain expressionsΒ #49075

Open
@jakebailey

Description

@jakebailey

Bug Report

πŸ”Ž Search Terms

undefined optional chain aliased condition narrowing

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried (from 4.4 onward, when we added aliased conditions).

⏯ Playground Link

Playground Link

πŸ’» Code

interface Foo {
    getValues(): number[];
}

declare const foo: Foo | undefined;

const vals = foo?.getValues();
if (vals) {
    foo; // Foo | undefined
}

const vals2 = foo && foo.getValues();
if (vals2) {
    foo; // Foo
}

if (foo?.getValues()) {
    foo; // Foo
}

πŸ™ Actual behavior

foo is potentially undefined in the first if block. The assignments fail.

(Added assignments so there's some feedback now that the playground's //^? doesn't work pre-4.6.)

πŸ™‚ Expected behavior

foo is narrowed to Foo in the first if block, matching the narrowing in the other if blocks.

Metadata

Metadata

Assignees

No one assigned

    Labels

    BugA bug in TypeScriptHelp WantedYou can do this

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions