From 7fcc3d56ef659f3c103ef41fb6a75e5a0d43444a Mon Sep 17 00:00:00 2001 From: Gabriel Nordeborn Date: Sun, 11 Aug 2024 18:41:07 +0200 Subject: [PATCH] document interface type generation trick --- .../docs/interfaces.md | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/rescript-relay-documentation/docs/interfaces.md b/rescript-relay-documentation/docs/interfaces.md index 1fd45afa..4fdaa1e3 100644 --- a/rescript-relay-documentation/docs/interfaces.md +++ b/rescript-relay-documentation/docs/interfaces.md @@ -108,4 +108,37 @@ let make = (~book) => { This way, we used the benefits of interfaces, but ended up having a bit harder time using its result. -> Note: Currently, this can't be improved much since these types are coming directly from the Relay compiler, so it's Relay itself that is a bit opinionated here in what types they output. It can get much more complex by adding more type specific fields, so as a workaround we recommend duplicating all field selections in inline fragment spread even if it removes most of the interface benefits. You can see more info on it [here](https://github.com/zth/rescript-relay/issues/315#issuecomment-1078739792). +Using the `@alias` directive together with a inline fragment spread, we can get the benefits of both of the approaches above: + +```rescript +module BookFragment = %relay(` + fragment MyComponent_book on Book { + title + ... @alias(as: "byType") { + __typename # You need to select this as well to get a variant back + ... on Textbook { + courses + } + ... on ColoringBook { + colors + } + } + } +`) + +@react.component +let make = (~book) => { + let book = BookFragment.use(book) + + // This exists directly on the object + let title = book.title + + // Can switch on `byType` to get the rest + switch book.byType { + | Textbook({courses}) => + | ColoringBook({colors}) => + | UnselectedUnionMember(typename) => + ("Unselected member type: " ++ typename)->React.string + } +} +```