Class Interop
new
Use bs.new
to emulate e.g. new Date()
:
REtype t;
[@bs.new] external createDate : unit => t = "Date";
let date = createDate();
Output:
JSvar date = new Date();
You can chain bs.new
and bs.module
if the JS module you're importing is itself a class:
REtype t;
[@bs.new] [@bs.module] external book : unit => t = "Book";
let bookInstance = book();
Output:
JSvar 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:
REclass 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.