sikanhe / gqtx

Code-first Typescript GraphQL Server without codegen or metaprogramming
458 stars 13 forks source link

Nullability of fields returning object types #31

Closed zth closed 3 years ago

zth commented 3 years ago

I have this field:

t.field("me", {
      type: UserType,
      resolve: (_, _args, ctx) => {
        return ctx.loggedInUserId
          ? ctx.dataLoaders.userById.load(ctx.loggedInUserId)
          : null;
      },
    }),

I'd expect this to work - I haven't marked UserType as non-nullable with t.NonNull(UserType), but this still errors with:

Type 'Promise<User | null> | null' is not assignable to type 'User | Promise<User>'.

Am I missing something in how this works, or have I found some form of bug?

zth commented 3 years ago

I was missing something... For anyone else with the same issue: I had explicitly annotated my User object type like this:

export const UserType: ObjectType<AppContext, User> = t.objectType<User>(...

...and making that annotation nullable made things work, like below:

export const UserType: ObjectType<AppContext, User | null> = t.objectType<User>(...

The reason for annotating this at all was that inference didn't work properly for me at some point. But I realize annotating like that at all is pretty weird.