Skip to content

Optional chaining control flow cannot narrow discriminated unions.Β #42120

@whzx5byb

Description

@whzx5byb

Bug Report

πŸ”Ž Search Terms

optional chaining discriminated union control flow

πŸ•— Version & Regression Information

  • This is the behavior in every version I tried.

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface Position {
  x: number;
  y: number;
  computed?: never;
}

interface RelativePosition {
  x: number | string;
  y: number | string;
  computed: Position;
}

declare var pos: Position | RelativePosition;

function getComputedX(pos: Position | RelativePosition): number {
  return pos.computed?.x ?? pos.x;
  // error here. Expect to be type "number", but actually "number | string";
}

if (pos.computed?.x !== undefined) {
  pos; // Expected to be type "RelativePosition", but actually "Position | RelativePosition"
  pos.computed; 
  // Inconsistence here. 
  // If "pos" is "Position | RelativePosition", then "pos.computed" should be "Position | undefined".
  // If "pos" is "RelativePosition", then "pos.computed" should be "Position". (And this is expected.)
  // But here "pos" is "Position | RelativePosition", but "pos.computed" is "Position".
  // The inconsistence make me think it is a bug instead of a suggestion.
}

Possibly related: #34597

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions