Reputation: 25032
I have a GraphQL (GQL) server and am using TypeScript (TS) on the front end. Here is my GQL type.
type AutomatedAlgorithmValue {
politicalEntityAlgorithmValueId: Long
politicalEntityId: Long!
...
}
politicalEntityId
is non-nullable. This gives me the behavior if I ask for politicalEntityId
, then it is guaranteed to be there, but if I don't ask for it then the query runs as normal.
I use graphql-codegenerator to create the TS types out of the GQL schema. The TS types makes the politicalEntityId
as non-null, so now on the front end I have to always request the politicalEntityId
as part of the AutomatedAlgorithmValue
type even if it isn't something that I want to request.
In my front end code, I am holding the data in a hook
let [results, setResults] = useState<AutomatedAlgorithmValue[]>([]);
Here is my GQL request
executeAutomatedAlgorithmProcess(politicalEntityId: $id, type: $type) {
values {
politicalEntityAlgorithmValueId
}
}
At this point I don't need the politicalEntityId
, but when I try to add the data to my results
, the TS compiler knows I am adding null
for the non-null
property politicalEntityId
and an error is thrown.
It gets even worse if there is a non-null
object with other non-null
properties, because now the request gets larger and larger with each unnecessary non-null
property/object.
How are others handling this? Do I have to create a new type each time? Do I use Pick
to determine what the data is going to be in the results
hook
? Is there a plugin that makes everything nullable and if so should I use that?
Upvotes: 1
Views: 1504
Reputation: 6884
So I think you're using a type that is generated based off your GraphQL schema using graphql-code-generator's typescript
plugin. As you are saying, these types have every field specified in the schema.
I believe what you also need to do is use the typescript-operations plugin. The typescript operations plugin basically does what you're talking about using Pick
, but does it automatically based on the frontend queries you have defined. So the types that the typescript operations plugin generates match the operations you declare.
You'll also oftentimes use a third plugin on top of these two as well that is specific for you client like react-query, react-apollo, urql, etc so you end up with ready to use hooks for each operation that have type safety.
Upvotes: 1