Skip to content

Union doesn't merge objects properties' type #8289

Closed

Description

TypeScript Version:

This is reproducible both in VSCode 1.0 and in the playground (https://www.typescriptlang.org/play/#src=...)

Code

interface A {
    x: number;
}

interface B {
    x: string;
}

const c: A | B = { x: 1 || "a" };

const d: A | B = { x: 1 } || { x: "a" };

Expected behavior:
Both c and d should be fine

Actual behavior:
TypeScript reports this error for the const c: A | B = { x: 1 || "a" }; statement:

Type '{ x: number | string; }' is not assignable to type 'A | B'.
  Type '{ x: number | string; }' is not assignable to type 'B'.
    Types of property 'x' are incompatible.
      Type 'number | string' is not assignable to type 'string'.
        Type 'number' is not assignable to type 'string'.

Activity

  1. changed the title [-]Union doesn't merge object properties' type[/-] [+]Union doesn't merge objects properties' type[/+] on Apr 25, 2016
  2. mhegazy commented on Apr 25, 2016

    @mhegazy
    Contributor

    { x: number | string }; is neither A nor B. it becomes easier to see that with more than one property, e.g.

    interface A {
        x: number;
        y:  number;
    }
    
    interface B {
        x: string;
        y: string;
    }
    
    const c: A | B = { x: 1 || "a" , y :  2 || "b"};
  3. RyanCavanaugh commented on Apr 25, 2016

    @RyanCavanaugh
    Member

    I should add that we've gotten this request around single-property types a bunch. It turns out to be very difficult to detect all of these cases properly in the compiler.

  4. nicolo-ribaudo commented on Apr 26, 2016

    @nicolo-ribaudo
    ContributorAuthor

    Mohamed Hegazy (@mhegazy) Thank you, now I see why the current behavior is correct

  5. locked and limited conversation to collaborators on Jun 19, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    QuestionAn issue which isn't directly actionable in code

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions