Skip to content
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

Destructuring breaks tagged union case inference #23613

Closed
bcherny opened this issue Apr 22, 2018 · 4 comments
Closed

Destructuring breaks tagged union case inference #23613

bcherny opened this issue Apr 22, 2018 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@bcherny
Copy link

bcherny commented Apr 22, 2018

TypeScript Version: 2.8.3

Search Terms: union, destructure

Code

type Message =
    { type: 'sendMessageToThread', data: { threadId: number, message: string }}
  | { type: 'createThread', data: { userIds: number[] }}
  | { type: 'addUserToThread', data: { threadId: number, userId: number }}

// Good case
function a(message: Message) {
  switch (message.type) {
    case 'sendMessageToThread':
      console.log(message.data.threadId)
  }
}

// Bad case
function b({ type, data }: Message) {
  switch (type) {
    case 'sendMessageToThread':
      // Error: Property 'threadId' does not exist on type
      console.log(data.threadId)
  }
}

Expected behavior:

TS should infer which case the tagged union falls into regardless of whether or not the parameter is destructured. data should be inferred as { threadId: number, message: string }.

Actual behavior:

data is inferred as the union of all data values in Message.

Playground Link

@mhegazy
Copy link
Contributor

mhegazy commented Apr 23, 2018

Duplicate of #14630, and #15482

@mhegazy mhegazy added the Duplicate An existing issue was already created label Apr 23, 2018
@bcherny
Copy link
Author

bcherny commented Apr 23, 2018

Thanks for digging up those issues @mhegazy. This seems like a real issue, so I'm not sure why those were closed out. Maybe it's worth keeping one of them open to track the issue? This is pretty surprising behavior from a user's point of view.

@mhegazy
Copy link
Contributor

mhegazy commented Apr 23, 2018

I would merge this in #9998. these are design limitation for how control flow analysis is implemented.

@bcherny
Copy link
Author

bcherny commented Apr 28, 2018

Sounds good to me.

@bcherny bcherny closed this as completed Apr 28, 2018
@microsoft microsoft locked and limited conversation to collaborators Jul 31, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

No branches or pull requests

2 participants