What is the recommended replacement for `@deriving(jsConverter)`

@deriving(jsConverter) has been deprecated for quite some time, but I have found hard to stop using it, especially the tFromJs when validating input that cannot be trusted to be correct.

What is the proposed alternative to FromJs? A hand written string => option<t> function?

My use case is basically always enums like:

@deriving(jsConverter)
type status = 
    | @as("draft") Draft
    | @as("in-progress") InProgress
    | @as("done") Done

Variant coercion:

This also enables you to have the catch-all case as part of the variant:

@unboxed
type status =
  | @as("draft") Draft
  | @as("in-progress") InProgress
  | @as("done") Done
  | Other(string)

let fromStatus = (Draft :> string)
let toStatus = ("done" :> status)
1 Like

you can also pattern-match on subtypes:

@unboxed
type status =
  | @as("draft") Draft
  | @as("in-progress") InProgress
  | @as("done") Done

module Raw = {
  @unboxed
  type t = | ...status | Other(string)
}

let fromString = (raw: string) =>
  switch (raw :> Raw.t) {
  | ...status as t => Some(t)
  | Other(_) => None
  }
2 Likes