Docs / BuckleScript / Class

Class Interop

new

Use bs.new to emulate e.g. new Date():

RE
type t; [@bs.new] external createDate : unit => t = "Date"; let date = createDate();

Output:

JS
var date = new Date();

You can chain bs.new and bs.module if the JS module you're importing is itself a class:

RE
type t; [@bs.new] [@bs.module] external book : unit => t = "Book"; let bookInstance = book();

Output:

JS
var Book = require("Book"); var bookInstance = new Book();

Bind to JS Classes

JS classes are really just JS objects wired up funnily. In general, prefer using the previous object section's features to bind to a JS object.

OCaml having classes really helps with modeling JS classes. Just add a [@bs] to a class type to turn them into a Js.t class:

RE
class type _rect = [@bs] { [@bs.set] pub height: int; [@bs.set] pub width: int; pub draw: unit => unit }; type rect = Js.t(_rect);

For Js.t classes, methods with arrow types are treated as real methods (automatically annotated with [@bs.meth]) while methods with non-arrow types are treated as properties. Adding bs.set to those methods will make them mutable, which enables you to set them using #= later. Dropping the bs.set attribute makes the method/property immutable. Basically like the object section's features.