Skip to content

Object destructuring loses type inference #27497

Closed
@Ky6uk

Description

@Ky6uk

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.

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