Skip to content

Union's resolveType doesn't know about __typename #188

@ThisIsMissEm

Description

@ThisIsMissEm

I'm currently trying to build a graphql server that uses the Result Union's pattern described by @sachee, whereby fields that may error in normal operation when resolving them return Union type of something like union PostResult = NotFound | Post

There's a video describing this pattern here: https://www.youtube.com/watch?v=GYBhHUGR1ZY

However, if you have:

export const PostResult = unionType({
  name: 'PostResult',
  description:
    'A Post, or NotFound if the post was not found',
  definition(t) {
    t.members('Post', 'NotFound');
    t.resolveType(item => item.__typename);
  }
});

Then you get an error telling you that __typename isn't a property of item, even though your resolver for the field that uses this PostResult union can definitely return the __typename field.

export const Query = objectType({
  name: 'Query',
  definition(t) {
    t.field('post', {
      type: PostResult,
      args: {
        id: idArg({ required: true })
      },
      resolve(root, { id }) {
        try {
          const post = await Posts.findById(id)
          return { __typename: "Post", ...post }
        } catch(err) {
          return { __typename: "NotFound", message: `Could not find post with ID: ${id}` }
        }
    });
  }
});

I think the type assigned to the callback argument in t.resolveType should have the __typename property available.

For now, I'm able to work-around this by using item['__typename'] but that's a pretty ugly hack.

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions