relay-tools / relay-compiler-language-typescript

⛔️ Obsolete - A language plugin for Relay that adds TypeScript support, including emitting type definitions.
MIT License
241 stars 70 forks source link

Union fields incorrectly generating type declarations #201

Open maraisr opened 4 years ago

maraisr commented 4 years ago

for the definition:

type PostNotFound implements Node {
    id: ID!;
}

type PostMoved implements Node {
    id: ID!;
    target: Post!;
}

type Post implements Node {
    id: ID!;
    body: String!;
    author: String!;
}

union BlogResult = Post | PostNotFound | PostMoved;

type Blog {
   node: BlogResult;
}

and the query:

query BlogPostQuery {
    blog {
        ... on PostNotFound {
            __typename
        }
        ... on Post {
            body
            author
        }
    }
}

Error:

The types generated doesn't allow me to discriminate unions:

export type BlogPostQuery = {
    readonly blog: {
        readonly __typename: "PostNotFound";
        readonly body?: string;
        readonly author?: string;
    }
}

To me that is wrong, because the typename PostNotFound doesnt have those fields on it.

Expected:

export type BlogPostQuery = {
    readonly blog: {
        readonly __typename: "PostNotFound";
    } | {
        readonly __typename: "Post";
        readonly body: string;
        readonly author: string;
    }
}

or would I need to ask for __typename on every union member, or on field for that matter.


Logging so I don't forget, will raise a fix PR soon

damikun commented 4 years ago

@maraisr i think you can solve it using separate fragments for each union inside your querry. It will spilit it to fragmentRefs..

query BlogPostQuery {
    blog {
        __typename  // Use this to differ

         ... PostNotFound_fragment 
     ... Post_fragment

    }
}

fragment PostNotFound_fragment on PostNotFound {
 ...
}

fragment Post_fragment on Post {
 ...
}