Skip to content

Type inference behave different with or without destructure #28599

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
lihz6 opened this issue Nov 19, 2018 · 3 comments
Closed

Type inference behave different with or without destructure #28599

lihz6 opened this issue Nov 19, 2018 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@lihz6
Copy link

lihz6 commented Nov 19, 2018

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.

@AlCalzone
Copy link
Contributor

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

@ahejlsberg
Copy link
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.

@ahejlsberg ahejlsberg added the Duplicate An existing issue was already created label Nov 19, 2018
@typescript-bot
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

4 participants