Skip to content

Commit c0cc5e1

Browse files
knpwrsstubailo
authored andcommitted
Update Learn-Schema.md -- Improve Union Type Examples (#635)
* Update Learn-Schema.md Add `__typename` to the query to show that union types can still be differentiated on the client and add a second example showing common fields being queried in one spot. * Add note about the use of `__typename`
1 parent 3286074 commit c0cc5e1

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

site/learn/Learn-Schema.md

+28
Original file line numberDiff line numberDiff line change
@@ -311,6 +311,7 @@ In this case, if you query a field that returns the `SearchResult` union type, y
311311
# { "graphiql": true}
312312
{
313313
search(text: "an") {
314+
__typename
314315
... on Human {
315316
name
316317
height
@@ -327,6 +328,33 @@ In this case, if you query a field that returns the `SearchResult` union type, y
327328
}
328329
```
329330

331+
The `__typename` field resolves to a `String` which lets you differentiate different data types from each other on the client.
332+
333+
Also, in this case, since `Human` and `Droid` share a common interface (`Character`), you can query their common fields in one place rather than having to repeat the same fields across multiple types:
334+
335+
```graphql
336+
{
337+
search(text: "an") {
338+
__typename
339+
... on Character {
340+
name
341+
}
342+
... on Human {
343+
height
344+
}
345+
... on Droid {
346+
primaryFunction
347+
}
348+
... on Starship {
349+
name
350+
length
351+
}
352+
}
353+
}
354+
```
355+
356+
Note that `name` is still specified on `Starship` because otherwise it wouldn't show up in the results given that `Starship` is not a `Character`!
357+
330358
### Input types
331359

332360
So far, we've only talked about passing scalar values, like enums or strings, as arguments into a field. But you can also easily pass complex objects. This is particularly valuable in the case of mutations, where you might want to pass in a whole object to be created. In the GraphQL schema language, input types look exactly the same as regular object types, but with the keyword `input` instead of `type`:

0 commit comments

Comments
 (0)