sikanhe / gqtx

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

Self referencing objectType has type any #37

Closed Ericnr closed 3 years ago

Ericnr commented 3 years ago

If my gql type defined with t.objectType references itself it TS type is any

// typeof GqlUser is any
const GqlUser = t.objectType<User>({
  name: 'User',
  fields: () => [
    t.defaultField('id', t.NonNull(t.ID)),
    t.defaultField('name', t.NonNull(t.String)),
    t.field('parent', {
      type: GqlUser,
      resolve: (parent, args, ctx, info) => {
        return 5; // accepts any value since GqlUser is any
      },
    }),
  ],
});
sikanhe commented 3 years ago

Good observation - unfortunately this is more of a typescript limitation. In the self recursive, or sometimes mutually recursive scenarios, You want to annotate the returning object. This should definitely be documented though.

import type { ObjectType } from 'gqtx'

const GqlUser: ObjectType<YourAppContext, User | null> = t.objectType<User>({
  name: 'User',
  fields: () => [
    t.defaultField('id', t.NonNull(t.ID)),
    t.defaultField('name', t.NonNull(t.String)),
    t.field('parent', {
      type: GqlUser,
      resolve: (parent, args, ctx, info) => {
        return 5; // accepts any value since GqlUser is any
      },
    }),
  ],
});
n1ru4l commented 3 years ago

We should hin that people should use ts strict mode, which will make this a ts error. See #52