Skip to content

Type inference behave different with or without destructure #28599

Closed

Description

@ngolin

TypeScript Version: 3.2.0-dev.201xxxxx

Search Terms: type inference behave different

Code

type Shape = {
  kind: 'circle',
  data: {
    radius: number
  }
} | {
  kind: 'square',
  data: {
    size: number
  }
};

function getAreaOkay(shape: Shape) {
  switch (shape.kind) {
    case 'circle':
      // okay
      return shape.data.radius;
  }
}
function getAreaFail({ kind, data }: Shape) {
  switch (kind) {
    case 'circle':
      // fail
      return data.radius;
  }
}

Expected behavior: the above two should be identical.

Actual behavior: they are not.

Activity

  1. AlCalzone commented on Nov 19, 2018

    @AlCalzone
    Contributor

    AFAIK, typescript doesn't narrow the type from one variable (kind) to a seperate one (data).

  2. ahejlsberg commented on Nov 19, 2018

    @ahejlsberg
    Member

    This is a duplicate of #23613 and several others like it. The core design limitation is that the control flow analyzer doesn't track mutually dependent variables. We're tracking the issue in #12184.

  3. typescript-bot commented on Dec 12, 2018

    @typescript-bot
    Contributor

    This issue has been marked as a duplicate and has seen no activity in the last day. It has been closed automatic house-keeping purposes.

  4. locked as resolved and limited conversation to collaborators on Oct 21, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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