typescript plugin: Resolvers and Optional vs Nullable types. #4345
-
I looked around for documentation on this but couldn't find anything. Apologies if this is redundant. I have a question about generated resolver types. My understanding of a resolver is that it returns the value the field is pointing to, and if the value is an object type, the resolver may return a partial value. e.g. if your schema is type Query {
user(id: ID!): User;
}
type User {
displayName: String!;
recentActivity: [Activity!]!;
}
type Activity {
description: String!;
} your resolver at Query.user might only resolve an object with However, the expected type for the resolver at Query.user is (after inlineing types): ResolverTypeWrapper<{displayName: string, recentActivity: Activity[]}> which requires you to always return recentActivity from your resolver. The problem seems to be coming from making all non-nullable graphql fields (e.g. must have a non-null value in the response when queried, with non-optional fields in typescript (e.g. must always be present in the value). To fix this problem, the typescript plugin could instead generate
But that means the default behaviour is to allow incomplete resolvers as opposed to explicitly requiring casts to opt-out of returning complete types. In a perfect world, resolvers returning partials could work and the check that a schema is complete could happen when constructing your resolver map. but I'm not sure how expressive typescript is for those scenarios. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Apologies if any of the concepts I'm referring to here are apollo-specific, I'm new to this ecosystem. |
Beta Was this translation helpful? Give feedback.
-
The default output of There are several solutions you can use:
You can read more about resolvers and codegen here: https://the-guild.dev/blog/better-type-safety-for-resolvers-with-graphql-codegen |
Beta Was this translation helpful? Give feedback.
The default output of
typescript-resolvers
is a 1:1 match of the JSON structure. That means, you can't have partials return values with the default settings.There are several solutions you can use:
defaultMapper: Partial<{T}>
. This will allow you to return partial values on resolvers.mappers
- In most cases, your data models are not the same as your GraphQL API. You can tell codegen where are your TypeScript types that represents each GraphQL type, and it will use those types instead of using the default types.You can read more about resolvers and codegen here: https://the-guild.dev/blog/better-type-safety-for-resolvers-with-g…