Thanks for the code snippet! This helps!
Looking at your CodeSandbox, I actually think you have this setup correctly, the problem is that there are cases where you expect a field to be non-nullable, but the return value of your resolver might return undefined. For example, this resolver:
Job: {
company: (job) => {
return DB_Company.findById(job.companyId)
},
},
I’m seeing the following error:
Type '(job: IJob) => Promise<ICompany | undefined>' is not assignable to type 'Resolver<ResolverTypeWrapper<ICompany>, IJob, any, {}> | undefined'.
Type '(job: IJob) => Promise<ICompany | undefined>' is not assignable to type 'ResolverFn<ResolverTypeWrapper<ICompany>, IJob, any, {}>'.
Type 'Promise<ICompany | undefined>' is not assignable to type 'ResolverTypeWrapper<ICompany> | Promise<ResolverTypeWrapper<ICompany>>'.
Type 'Promise<ICompany | undefined>' is not assignable to type 'Promise<ICompany>'.typescript(2322)
Pay close attention to the last line and this becomes apparent:
Type 'Promise<ICompany | undefined>' is not assignable to type 'Promise<ICompany>'.typescript(2322)
This is the return value that is incorrect from your resolver.
Here, your DB_Company.findById(id)
might return undefined
, but you’ve specified in your schema that its a non-null field. You can either make this a nullable field, or do something like this to fix the issue:
Job: {
company: async (job) => {
const company = await DB_Company.findById(job.companyId);
if (!company) {
throw new Error('Company not found');
}
return company;
},
},
The error on Query.company
is a bit more obscure. The issue here is that your resolver expect a return value of Maybe<ResolversTypes['Company']>
, where Maybe
is defined as type Maybe<T> = T | null
. I see this particular resolver might return undefined
, which is not compatible with null
. You’ll either need to explicitly return null when the value is missing:
Query: {
company: async (_root, { id }) => {
const company = await DB_Company.findById(id);
return company || null;
}
},
or you can update your codgen config to set the maybeValue
to something that includes undefined
:
# codgen.yml
generates:
'path/to/file.ts':
plugins: ['typescript']
config:
maybeValue: 'T | null | undefined'
I found both of these to clear up the type errors you’re seeing.
That Resolver
type signature is a bit hard to read since it takes 4 generic values. The first 2 generic parameters are the ones that you care about the most. The first generic type is the return value of the resolver, and the second generic type is the parent type for the resolver (the type of the thing passed as the first argument to the resolver function).
Hope this helps!