Microsoft/TypeScript

Condition aliasing doesn't capture optional chain expressions

Open

#49.075 aberto em 11 de mai. de 2022

Ver no GitHub
 (4 comments) (1 reaction) (0 assignees)TypeScript (6.726 forks)batch import
BugDomain: check: Control FlowHelp Wanted

Métricas do repositório

Stars
 (48.455 stars)
Métricas de merge de PR
 (Mesclagem média 6d 17h) (9 fundiu PRs em 30d)

Description

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.

Guia do colaborador