Skip to content

Unexpected behavior of union of interfaces sharing property with the same name. #7780

Closed
@MrQubo

Description

@MrQubo

TypeScript Version:

1.8.9

Code

Starting point:

type Type = 'foo' | 'bar';

interface FieldProto {
    type: Type;
}

interface FooField extends FieldProto {
    type: 'foo';
    foo?: string;
}

interface BarField extends FieldProto {
    type: 'bar';
    bar?: string;
}

type Field = FooField | BarField;

First case:

let type: Type = 'foo';

let field: Field = {
    type: type
};

Second case:

let field: Field = {
    type: 'foo',
    bar: 'eggs'
};

Expected behavior:

Type { type: 'foo' | 'bar', bar: 'eggs' } shouldn't be assignable to type Field.
Type { type: 'foo' | 'bar' } should be assignable to type Field.
Type { type: 'bar', bar: 'eggs' } should be assignable to type Field.
Type { type: 'foo', bar: 'eggs' } shouldn't be assignable to type Field.

Actual behavior:

Both of types { type: 'foo' | 'bar', bar: 'eggs' } and { type: 'foo' | 'bar' } aren't assignable to type Field.
Both of types { type: 'bar', bar: 'eggs' } and { type: 'foo', bar: 'eggs' } are assignable to type Field.

First case compiles with an error:

test3.ts(21,5): error TS2322: Type '{ type: "foo" | "bar"; }' is not assignable to type 'FooField | BarField'.
  Type '{ type: "foo" | "bar"; }' is not assignable to type 'BarField'.
    Types of property 'type' are incompatible.
      Type '"foo" | "bar"' is not assignable to type '"bar"'.
        Type '"foo"' is not assignable to type '"bar"'.

Second case compiles without an error.

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