How to solve default value when destructuring?

Hello I am a freshman,and I have a problem on learning.
in Javascript, sometimes we use default value with destructuring, like this:
let {width = 100, height = 200, title} = options
and in Rescript I try to use a record to describe the config options with optional record fields,But when I try to destructuring:

type options = {

  width?: int,

  height?: int,

}

let test = (options: options) => {

  let {width, height} = options

}

it will remind me “forgot to handle a possible case here”, But i don’t know how to solve and give a default value. Could anyone give me some tips? would it better to bind the let one by one? is that a surgar of pattern matching similar to below and how to solve elegant?

type options = {

  width?: int,

  height?: int,

}

let test = (options: options) => {

  let {width, height} = switch options{
     |{width:Some("dont know what to fill"),height:None}=>{"balabala"}
     |{width:None,height:Some("dont know what to fill")}=>{"balabala"}
     |{width:Some("dont know what to fill"),height:Some("dont know what to fill")}=>{"balabala"}
     |{width:None,height:None}=>{"balabala"}
  }

You can just access each one individually

let width = switch options.width {
| Some(val) => val
| None => 0
}

let height = switch options.height {/** ... */}

If you have a lot of default options, you can create a utility function to help with it

let getWithDefault = (option, defaultValue) =>
  switch option {
  | Some(value) => value
  | None => defaultValue
  }

let width = options.width->getWithDefault(0)
let height = options.width->getWithDefault(0)

Luckily, this function already exists in rescript Belt, which is a builtin set of utility functions

Belt.Option | ReScript API (rescript-lang.org)

let width = options->Belt.Option.getWithDefault(0)
let height = options->Belt.Option.getWithDefault(0)
3 Likes

Side note: if you’re working with an “options” object that is just meant to pass named variables to a function, you can use built in Labeled Arguments to do that instead of making a new type

let test = (~width = 0, ~height = 0, ()) => {
 // do stuff
}

test(~width=1, ())

Function | ReScript Language Manual (rescript-lang.org)

2 Likes

Thanks for your help!