How to define dom types?

How I switched from typescript to rescript ?

   function init(
        dom: HTMLDivElement | HTMLCanvasElement
    ): Something;

ReScript doesn’t come with built-in DOM bindings. You can install or define your own types and bindings.


I was wrong. There’re built-in DOM types: Dom | ReScript API . But no functions to operate on them:

The Dom module offers a canonical set of dom related types that third party libraries can depend on. It only provides types, no functions to manipulate the values of certain types whatsoever.

assuming that init function is already coded in js and you want to use it from rescript

type divElement = ...
type canvasElement = ...
type something = ...

@val external initWithDiv: (divElement) => something = "init"
@val external initWithCanvas: (canvasElement) => something = "init"
type element = 
| Canvas(Dom.htmlCanvasElement)
| Div(Dom.htmlDivElement)

type something = 
| SomethingWithCanvas(Dom.htmlCanvasElement)
| SomethingWithDiv(Dom.htmlDivElement)

let init = (dom) => {
  switch dom {
  | Canvas(element) => SomethingWithCanvas(element)
  | Div(element) => SomethingWithDiv(element)

This is the right general approach imho. Note that the types are already defined in the Dom module e.g. Dom | ReScript API

The rescript-webapi library internally uses the Dom types to preserve compatibility across libraries.

1 Like