Docs / Language Manual / Interop Cheatsheet
Edit

Interop Cheatsheet

This is a glossary with examples. All the features are described by later pages.

List of Decorators

Note: In previous versions (< 8.3) all our attributes started with a bs. prefix. Our formatter will automatically drop them in newer ReScript versions.

Attributes

Extension Points

Raw JS

ReScriptJS Output
let add = %raw("(a, b) => a + b")
%%raw("const a = 1")

Global Value

ReScriptJS Output
@val external setTimeout: (unit => unit, int) => float = "setTimeout"

Global Module's Value

ReScriptJS Output
@val @scope("Math")
external random: unit => float = "random"

let someNumber = random()

@val @scope(("window", "location", "ancestorOrigins"))
external length: int = "length"

Nullable

ReScriptJS Output
let a = Some(5) // compiles to 5
let b = None // compiles to undefined

Handling a value that can be undefined and null, by ditching the option type and using Js.Nullable.t:

ReScriptJS Output
let jsNull = Js.Nullable.null
let jsUndefined = Js.Nullable.undefined
let result1: Js.Nullable.t<string> = Js.Nullable.return("hello")
let result2: Js.Nullable.t<int> = Js.Nullable.fromOption(Some(10))
let result3: option<int> = Js.Nullable.toOption(Js.Nullable.return(10))

JS Object

Function

Object Method & Chaining

ReScriptJS Output
@send external map: (array<'a>, 'a => 'b) => array<'b> = "map"
@send external filter: (array<'a>, 'a => 'b) => array<'b> = "filter"
[1, 2, 3]
  ->map(a => a + 1)
  ->filter(a => mod(a, 2) == 0)
  ->Js.log

Variadic Arguments

ReScriptJS Output
@module("path") @variadic
external join: array<string> => string = "join"

Polymorphic Function

ReScriptJS Output
@module("Drawing") external drawCat: unit => unit = "draw"
@module("Drawing") external drawDog: (~giveName: string) => unit = "draw"
ReScriptJS Output
@val
external padLeft: (
  string,
  @unwrap [
    | #Str(string)
    | #Int(int)
  ])
  => string = "padLeft"

padLeft("Hello World", #Int(4))
padLeft("Hello World", #Str("Message from ReScript: "))

JS Module Interop

See here

Dangerous Type Cast

Final escape hatch converter. Do not abuse.

ReScriptJS Output
external convertToFloat: int => float = "%identity"
let age = 10
let gpa = 2.1 +. convertToFloat(age)