Docs / BuckleScript / InteropMisc

Interop Miscellaneous

Composing bs Attributes

As you might have guessed, most bs.* attributes can be used together. Here's an extreme example:

Note that bs.splice was renamed to bs.variadic after version 4.08

RE
[@bs.val] [@bs.scope "global"] [@bs.variadic] external draw : ([@bs.as "dog"] _, array(int)) => unit = "draw"; draw([|1, 2|]);

Output:

JS
global.draw("dog", 1, 2);

Safe External Data Handling

In some cases, the data could either come from JS or BS; it's very hard to give precise type information because of this. For example, for an external promise whose creation could come from the JS API, its failed value caused by Promise.reject could be of any shape.

BuckleScript provides a solution, bs.open, to filter out OCaml structured exception data from the mixed data source. It preserves type safety while allowing you to deal with mixed source. It makes use of OCaml’s extensible variant, so that users can mix values of type exn with JS data.

RE
let handleData = [@bs.open] ( fun | Invalid_argument(_) => 0 | Not_found => 1 | Sys_error(_) => 2 ); /* handleData is 'a => option(int) */

For any input source, as long as it matches the exception pattern (nested pattern match supported), the matched value is returned, otherwise return None.