Skip to content

Object destructuring loses type inference #27497

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
Ky6uk opened this issue Oct 2, 2018 · 2 comments
Closed

Object destructuring loses type inference #27497

Ky6uk opened this issue Oct 2, 2018 · 2 comments
Labels
Duplicate An existing issue was already created

Comments

@Ky6uk
Copy link

Ky6uk commented Oct 2, 2018

TypeScript Version: 3.1.1

Search Terms:

  • type inference, destructuring, type narrowing

Code

interface A {
  hasValue: true;
  value: string;
}

interface B {
  hasValue: false;
}

function checkOne(args: A | B) {
  return args.hasValue && args.value;
  //                           ^^^^^ this is ok, 'args' infers type A
}

function checkTwo(args: A | B) {
  const { hasValue } = args;

  return hasValue && args.value;
  //                      ^^^^^ Error: Property 'value' does not exist on type 'B'.
}

Expected behavior:
Both checkOne and checkTwo compiled without errors.

Actual behavior:
Function checkTwo has compilation errors.

Playground Link: typescriptlang.org

Related Issues: I can't find related issues, but I am sure this is already known issue.

@MartinJohns
Copy link
Contributor

MartinJohns commented Oct 2, 2018

It does not "lose" type inference, the type inference just does not work the way you expect it. You're not checking args.hasValue (which would narrow the type to A), you're checking hasValue. The TypeScript compiler does not make the connection "hasValue comes from args, so by checking hasValue I can narrow args". It's unrelated to the destructuring, you have the same issues if you just assign it to a variable: const hasValue = args.hasValue.

There are numerous issues about this exact issue, that the type narrowing is not tracked across variables.

@MarcosAtApprentice
Copy link

MarcosAtApprentice commented Jul 26, 2021

How can I work around this and force typescript to infer the type from the assignment?

Edit: seems like this should be working starting with Typescript 4.4 (#44730)

Edit2: Not working, posted in that same PR about the weird issue I'm having: #44730 (comment)

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