Skip to content

Unexpected behavior with conditional type when using with object destructuring #40647

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
deebov opened this issue Sep 19, 2020 · 3 comments
Closed
Labels
Duplicate An existing issue was already created

Comments

@deebov
Copy link

deebov commented Sep 19, 2020

Getting weird behavior with conditional types when using them with object destructuring. I think the code explains better than words in this situation. Please, go to the playground

TypeScript Version: 4.0.3

Search Terms: object destructuring, conditional object destructuring

Code

type Props =
  | {
    direction: "horizontal" | "vertical";
    onChange: (value: number) => void;
  }
  | {
    direction: "both";
    onChange: ({ x, y }: { x: number; y: number }) => void;
  };


const notWorking = ({ onChange, direction }: Props) => {
  if (direction === 'horizontal') {
    onChange(2)
  }

  if (direction === 'both') {
    onChange({ x: 8, y: 4 })
  }
}

const notWorking2 = (props: Props) => {
  const onChange = props.onChange
  const direction = props.direction
  
  if (direction === 'horizontal') {
    onChange(2)
  }

  if (direction === 'both') {
    onChange({ x: 8, y: 4 })
  }
}

const working = (props: Props) => {
  if (props.direction === 'horizontal') {
    props.onChange(3)
  }

  if (props.direction === 'both') {
    props.onChange({ x: 8, y: 4 })
  }
}

Expected behavior:

Actual behavior:

Playground Link: playground link

Related Issues: -

@MartinJohns
Copy link
Contributor

Duplicate of #12184.

And on a side-note: There is no "conditional type" in your example. You're having a discriminated union type.

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Sep 22, 2020
@RyanCavanaugh
Copy link
Member

Thanks as usual @MartinJohns

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for 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