BuckleScript

BuckleScript

  • Docs
  • Try
  • API
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Interop

Intro

  • What & Why
  • Installation
  • New Project
  • Try
  • Concepts Overview
  • Upgrade Guide to v7

Interop

  • Overview
  • Cheatsheet
  • Embed Raw JavaScript
  • Common Data Types
  • Intro to External
  • Bind to Global Values
  • Null, Undefined & Option
  • Object
  • Object 2
  • Class
  • Function
  • Property access
  • Return value wrapping
  • Import & Export
  • Regular Expression
  • Exceptions
  • JSON
  • Pipe First
  • Generate Converters & Helpers
  • Better Data Structures Printing (Debug Mode)
  • NodeJS Special Variables
  • Miscellaneous
  • Browser Support & Polyfills

Build System

  • Overview
  • Configuration
  • Automatic Interface Generation
  • Interop with Other Build System
  • Performance
  • Advanced

Standard Library

  • Overview

Advanced

  • Conditional Compilation
  • Extended Compiler Options
  • Use Existing OCaml Libraries
  • Difference from Native OCaml
  • Compiler Architecture & Principles
  • Comparison to Js_of_ocaml
Edit

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

external draw: (_ [@bs.as "dog"]) -> int array -> unit = "draw" [@@bs.val] [@@bs.scope "global"] [@@bs.variadic]

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

draw([|1, 2|]);

Output:

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.

let handleData = function [@bs.open]
 | Invalid_argument _ -> 0
 | Not_found -> 1
 | Sys_error _ -> 2

(* handleData is 'a -> int option *)
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.

Last updated on 4/13/2020
← NodeJS Special VariablesBrowser Support & Polyfills →
  • Composing bs Attributes
  • Safe External Data Handling