Skip to content

Optional chaining discards contextual type data #57645

Closed as not planned
Closed as not planned
@dgetu

Description

@dgetu

🔎 Search Terms

contextual type
optional chaining
subtype reduction
control flow analysis

🕗 Version & Regression Information

  • This is the behavior in every version I tried, and I reviewed the FAQ for entries about contextual typing

Optional chaining was introduced in 3.7, and 3.7 has the same behavior.

⏯ Playground Link

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgGIHt3IN4ChnIBGcUA-AFzICCUUcAngDwgCuAtodAHwDcuAvrgToQAZzDIYmZAF5kLEABMIMUBEXI4otNIA+8pSrWK+wGMgAUAQinpSAOmJQAlDnzIA9B+QRgYABbQktLoUEQkyP5ayABucAA2LCgABgrKqiDqye7CYhIScrYOTnwEXsgAKsii-ugs8RqcyGD0AA4paUaZitkELe2Vss1tEOjmYKXIueLhAF6UFgAelDR0TKwc3Mj6nRnqrjJcsejAGnJLlBUHR3gEBNPo8RD20FChFgBEAcDaWqLAAHMQGwIOBqrV6ooQAByCTCNitYBPD7OSb8PiCIA

💻 Code

interface Foo {
  bar?: Array<number>;
}
const foo = undefined as Foo | undefined;
if (!foo?.bar) {
  // either foo or bar has value `undefined`
  const t = foo?.bar;
  // T should be type `undefined`
  type T = typeof t;
  const baz: (x: Array<number> | undefined) => void = (x: T) => {
    console.error("this assignment shouldn't get past the type checker");
  };
}

🙁 Actual behavior

Type T has type Array<number> | undefined, even though the conditional implies that the value of t is falsy.

🙂 Expected behavior

The compiler should say that foo.bar is undefined in the scope of the then branch of the if statement.

Additional information about the issue

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Design LimitationConstraints of the existing architecture prevent this from being fixed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions