Class
new
Use bs.new
to emulate e.g. new Date()
:
type t
external createDate : unit -> t = "Date" [@@bs.new]
let date = createDate ()
type t;
[@bs.new] external createDate : unit => t = "Date";
let date = createDate();
Output:
var date = new Date();
You can chain bs.new
and bs.module
if the JS module you're importing is itself a class:
type t
external book : unit -> t = "Book" [@@bs.new] [@@bs.module]
let bookInstance = book ()
type t;
[@bs.new] [@bs.module] external book : unit => t = "Book";
let bookInstance = book();
Output:
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:
class type _rect = object
method height : int [@@bs.set]
method width : int [@@bs.set]
method draw : unit -> unit
end [@bs]
type rect = _rect Js.t
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.