[Beginner-Help] [FFI] Need help in decoding an object

I’d also follow the approach of having multiple functions that accept different numbers of arguments. I only recommend replacing the Arg.t with the Js.Json.t type to make it typesafe. Because with Arg.t you cast the type to the desired value without any guarantee that it’s what you expect.

This will be unneeded in favor of action2 if you use Js.Json.t.

The reason is that {..} is an object type. To access an object field you need to use options["first"] syntax instead of options.first.

It looks ok. The only change I’d have is to start using optional labeled arguments:

type defaultValue =
  | String(string)
  | Boolean(bool)
  | StringArr(array<string>)
@send
external option: (t, string, ~description: string=?, ~defaultValue: defaultValue=?, ()) => t = "option"

And we usually don’t add the Type postfix to the type names.

1 Like

There’s an error in my example, you’ll actually need to extract the value from the variant before passing it to the external option.

type defaultValue =
  | String(string)
  | Boolean(bool)
  | StringArr(array<string>)
@send
external _option: (t, string, ~description: string=?, ~defaultValue: Js.Json.t=?, ()) => t = "option"
let option = (commander, optionDefenition, ~description=?, ~defaultValue as maybeDefaultValue=?, ()) => {
  commander->_option(optionDefenition, ~description?, ~defaultValue?=maybeDefaultValue->Option.map(defaultValue => switch defaultValue {
  | String(string) => string->Js.Json.string
  | Boolean(boolean) => boolean->Js.Json.boolean
  | StringArray(stringArray) => stringArray->Js.Json.stringArray
})
}

Not sure the code above compiles, but I hope the idea is clear.

Although in your case, it’s better to set a default value while parsing arguments from action instead of passing it to option.

1 Like

You might need @variadic?

Does @variadic work for callbacks since action is a callback function