Skip to content

error casting interface union field #20889

@codemau5

Description

@codemau5

TypeScript Version: 2.6.2

Code

interface A1 {
    type: "A1";
}
interface A2 {
    type: "A2";
}
type AU = A1 | A2;

function foo(obj1: AU) {
    const obj2: AU = {
        type: obj1.type
        /*
        Error TS2322:
        Type '{ type: "A1" | "A2"; }' is not assignable to type 'AU'.
            Type '{ type: "A1" | "A2"; }' is not assignable to type 'A2'.
            Types of property 'type' are incompatible.
            Type '"A1" | "A2"' is not assignable to type '"A2"'.
            Type '"A1"' is not assignable to type '"A2"'.
        */

    };
}

Expected behavior:
create a new object with the same value of the first object.

Actual behavior:
typescript error TS2322:
Type '{ type: "A1" | "A2"; }' is not assignable to type 'AU'.
Type '{ type: "A1" | "A2"; }' is not assignable to type 'A2'.
Types of property 'type' are incompatible.
Type '"A1" | "A2"' is not assignable to type '"A2"'.
Type '"A1"' is not assignable to type '"A2"'.

exampe in TypesSript Playground:
https://www.typescriptlang.org/play/index.html#src=interface%20A1%20%7B%0D%0A%20%20%20%20type%3A%20%22A1%22%3B%0D%0A%7D%0D%0Ainterface%20A2%20%7B%0D%0A%20%20%20%20type%3A%20%22A2%22%3B%0D%0A%7D%0D%0A%0D%0Atype%20AU%20%3D%20A1%20%7C%20A2%3B%0D%0A%0D%0Afunction%20foo(obj1%3A%20AU)%20%7B%0D%0A%20%20%20%20const%20obj2%3A%20AU%20%3D%20%7B%0D%0A%20%20%20%20%20%20%20%20type%3A%20obj1.type%0D%0A%20%20%20%20%7D%3B%0D%0A%7D%0D%0A

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions