Quantcast
Channel: ReScript Forum - Latest posts
Viewing all articles
Browse latest Browse all 2592

Need help with binding to a function with a complex type

$
0
0

Welcome to the wonderful world of ReScript!

That example is quite tricky, but there are ways to handle it.

First, I would simplify the parameterType to this:

type parameterType =
  | @as("string") String
  | @as("number") Number
  | @as("boolean") Boolean

because according to your usage, you just pass
{name: "index", type: "number"} and not {name: "index", type: number(123)}, so no need to give the variants arguments IMO.

Second, if the ReScript type definition can be equivalent to the TS one, you don’t need a type parameter 'a for the parameterDefinition :

type parameterDefinition = {
  name: string,
  @as("type") type_: parameterType
}

Third, and admittedly this needs to be documented better, by combining unboxed variants and the tag decorator, you can create different variants from the same object, and the tag does not even have to be a string:

@tag("success")
type parseResult =
  | @as(true) Success({parameters: Js.Dict.t<parameterType>})
  | @as(false) Failure({reply: string})

This is a combination of your resultFailure and resultSuccess types. We set the tag to the success field. If it is true, then ReScript’s type system will treat it as a Success variant, if it’s false, then it will be a Failure variant.

Here is a full example on the ReScript playground.


Viewing all articles
Browse latest Browse all 2592

Trending Articles