How to convert record to object?

For example, Simply convert record:
{name: “John”, age:20}
to obj:
{“name”: “John”, “age”:20}

And how to get a subset of an object, like on get:
{“name”: “John”}
from above.

Also, is there a Rescript version of Partial<'t>?

Could you elaborate on the reason, why you want to convert a record to an object?

With the upcoming release of rescript v11 you can use “type coercion operator” :> to reduce a record type to a subset of it like this:

type a = {x: int}

type b = {
  ...a,
  y: bool,
}

let f: a => int = a => a.x

let recordA: a = {x: 3}
let recordB: b = {x: 42, y: true}

let works = recordA->f
// let fails = recordB->f

let success = (recordB :> a)->f

example at the playground

Edit: thanks to @flo-pereira, I updated the example to what I wanted to show and fixed my oversight. Coercing a record of type a to a doesn’t really make sense and the formatter even had removed it entirely from the example. I wanted to show, how to coerce a record of type b to type a.

1 Like

let success = (recordB :> a)->f

I met this problem while dealing with GraphQL + Apollo. There are multiple queries that return structurally equivalent yet nominally different types. I want to handle the these polymorphically (in pseudo-rescript):

let result = switch cases {
| case1 => MyQuery.A.use(arg)
| case2 => MyQuery.B.use(arg)
}

but I can’t, as these two have different types—something like MyQuery.A.A_inner.t and MyQuery.B.B_inner.t. Maybe the coercion operator from v11 might help, but Apollo client bindings + graphql-ppx stack does not support v11 yet. Is Obj.magic the only way to bypass the typechecker?

Do the queries return the same type? (as specified by the gql schema)
If so, you can use fragments. A defined fragment (using gql ppx) can be used several times and the ppx will only generate a single type for this fragment. Therefore, if all your query results just return the same fragment, they will all have the same type as their result.

Walnut is supposedly working on migrating graphql-ppx to v11: Anyone using graphql-ppx and rescript-apollo-client with 11? - #4 by jfrolich

3 Likes

Thank you for the link! So using fragments was the answer to my XY problem :slight_smile:

otherwise you can also use the excellent rescript-relay that works perfectly with v11.

2 Likes

Relay does seem really promising—especially the baked-in pagination support!
So to use Relay, I should replace Apollo with this, right?

Yes that’s right! Ideally your graphql server should be compatible with relay too.

I’m using Hasura and the doc says it supports Relay, so I guess I’m ready! :tada:

1 Like