Use bs.new
to emulate e.g. new Date()
:
typet; [@bs.new] externalcreateDate:unit => t="Date";letdate= createDate();
Output:
vardate=newDate();
You can chain bs.new
and bs.module
if the JS module you're importing is itself a class:
typet; [@bs.new] [@bs.module] externalbook:unit => t="Book";letbookInstance= book();
Output:
varBook=require("Book");varbookInstance=newBook();
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:
classtype _rect = [@bs] { [@bs.set] pub height: int; [@bs.set] pub width: int; pub draw: unit => unit };typerect=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.