You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is extending on `ResolversUnionTypes` implemented in https://github.com/dotansimha/graphql-code-generator/pull/9069
9
+
10
+
`resolversNonOptionalTypename` adds non-optional `__typename` to union members of `ResolversUnionTypes`, without affecting the union members' base intefaces.
11
+
12
+
A common use case for non-optional `__typename` of union members is using it as the common field to work out the final schema type. This makes implementing the union's `__resolveType` very simple as we can use `__typename` to decide which union member the resolved object is. Without this, we have to check the existence of field/s on the incoming object which could be verbose.
*With non-optional `__typename`:* Resolvers declare the type. This which gives us better TypeScript support in resolvers and simplify `__resolveType` implementation:
68
+
69
+
```ts
70
+
// Query/book.ts
71
+
exportconst book =async () => {
72
+
try {
73
+
const book =awaitfetchBook();
74
+
// 1. `__typename` is declared in resolver results...
75
+
return {
76
+
__typename: 'BookResult', // 1a. this also types `node` for us 🎉
77
+
node: book
78
+
}
79
+
} catch(e) {
80
+
return {
81
+
__typename: 'PayloadError',
82
+
message: "Failed to fetch book"
83
+
}
84
+
}
85
+
}
86
+
87
+
// BookPayload.ts
88
+
exportconst BookPayload = {
89
+
__resolveType: (parent) =>parent.__typename, // 2. ... means a very simple check in `__resolveType`
90
+
}
91
+
```
92
+
93
+
*Using `resolversNonOptionalTypename`:* add it into `typescript-resolvers` plugin config:
94
+
95
+
```ts
96
+
// codegen.ts
97
+
const config:CodegenConfig= {
98
+
schema: 'src/schema/**/*.graphql',
99
+
generates: {
100
+
'src/schema/types.ts': {
101
+
plugins: ['typescript', 'typescript-resolvers'],
102
+
config: {
103
+
resolversNonOptionalTypename: true// Or `resolversNonOptionalTypename: { unionMember: true }`
* @description Turning this flag to `true` will generate resolver signature that has only `resolveType` for interfaces, forcing developers to write inherited type resolvers in the type itself.
538
540
*/
539
541
onlyResolveTypeForInterfaces?: boolean;
542
+
/**
543
+
* @description Makes `__typename` of resolver mappings non-optional without affecting the base types.
0 commit comments