avoidOptionals globally, for all typestrue for output types (since empty values are returned as null, not undefined in the responses), but set it to false for input types (since variables treat undefined as null and it's a normal practice to omit empty values when providing variables, rather than providing nullsHi @yoavain-sundaysky ! Thank you for reporting this issue.
You are right, at the moment the optionals configuration can only be turned on/off and is not configurable.
We can give it a try in the future and add it (and we always welcome PRs).
An example use case for avoidOptionals is to model mock data in strictly the same way the server would return it, i.e., with null for requested nullable fields. Meanwhile, nullable fields in variable and input types should still be optional, because being able to elide the fields is also how it works in GraphQL, and having to always explicitly provide a null or [] is verbose and poor DX.
A workaround to currently avoid using avoidOptionals is a helper that removes optionality:
type DeepNonNullable<T> = {
[P in keyof T]-?: T[P] extends {} ? DeepNonNullable<T[P]> : T[P];
}
Implemented in https://github.com/dotansimha/graphql-code-generator/pull/2191 . Thanks @ekfn
Available in 1.5.0 馃帀
@dotansimha it doesn't look like this issue should be closed yet. In my testing, #2191 fixes this issue for the typescript plugin, but not for the typescript-operations plugin.
It appears that typescript-operations still only accepts a boolean value for avoidOptionals. Attempting to pass an object value is treated the same as passing avoidOptionals: true.
This issue popped up for me when I attempted to set a global avoidOptionals object config value in my graphql-codegen config file. The avoidOptionals object was treated as true by typescript-operations.
I think there is an easy work-around for this issue though (it's certainly an easy work-around for me): only set the avoidOptionals config to an object value when generating the "global" types file (i.e. don't define avoidOptionals globally). In my app at least, all of the typescript-operations type files only have input object types defined within them (so you don't need the ability to differentiate between object/input object types).
@thefliik you are right, I added a validation for the type of avoidOptionals in typescript-operations:
avoidOptionals: typeof config.avoidOptionals === 'boolean' ? getConfigValue(config.avoidOptionals, false) : false,
Now it will ignore the object value if it set globally.
Fixed in 1.6.0
Most helpful comment
@thefliik you are right, I added a validation for the type of
avoidOptionalsintypescript-operations:Now it will ignore the object value if it set globally.