Skip to content

Learning ReScript

A quick tour of ReScript syntax, with examples and links to the official docs for deeper study.

docs/learning-rescript.md
Raw Markdown

ReScript compiles to readable JavaScript and fits into the same runtime, npm packages, and tooling you already use. What it changes is how precisely you can model data and program behavior before the code ships.

A first look

The point of ReScript isn't just that types are nice. It lets you model the real states of your program, so the compiler enforces rules you'd otherwise keep in your head.

In many codebases, a value like this ends up spread across string values, nullable fields, and defensive checks. It works until one branch is forgotten during a refactor. ReScript pushes that information into the type itself:

1type user =
2 | Guest
3 | SignedIn(string)
4 | Banned(string)
5
6let greeting = user =>
7 switch user {
8 | Guest => "Welcome, stranger"
9 | SignedIn(name) => `Hello, ${name}`
10 | Banned(reason) => `Access denied: ${reason}`
11 }

A few things matter here:

  • type user declares a variant — a closed set of cases. The compiler knows every value user can hold.
  • switch matches each case directly. Add a new case to user later (say, Suspended ), and the compiler points out every switch that no longer covers the type.
  • The function reads like straightforward application code, but the guarantees are stronger: there is no ambiguity about what shape can arrive at runtime.
  • Types are inferred, so greeting does not need an annotation. You get compiler help without turning the example into a wall of type syntax.
  • Template strings use backticks and ${...} for interpolation, like in modern JavaScript.

This is the practical case for ReScript: instead of relying on conventions, comments, or discipline to keep state handling correct, you encode the valid cases once and let the compiler enforce them everywhere.

Exhaustiveness checking is on by default. You cannot ship a switch with a missing case, which removes a whole class of forgotten-state bugs before the code runs.

Let bindings and functions

Most values are declared with let. Functions take their arguments in parentheses.

1let count = 1
2let add = (a, b) => a + b
3
4let total = add(count, 41)

Bindings are immutable by default. That usually makes code easier to follow because values do not quietly change underneath you.

Records and variants

Records are object-like data with known fields. Variants are a fixed set of cases.

1type user = {
2 name: string,
3 admin: bool,
4}
5
6type status =
7 | Idle
8 | Saving
9 | Failed(string)
10
11let currentUser = {name: "Ada", admin: true}
12let currentStatus = Saving

Variants are especially useful anywhere a value can be in one of several known states. You model the allowed cases once, then the compiler checks every place that consumes them.

Pattern matching with switch

switch is the main branching construct. It handles destructuring and case coverage in one place.

1let statusLabel = status =>
2 switch status {
3 | Idle => "Ready"
4 | Saving => "Saving..."
5 | Failed(message) => `Failed: ${message}`
6 }

If you add a new variant case later, the compiler points out every switch that needs updating. The same applies when you match on records, tuples, or nested data:

1type role =
2 | Guest
3 | Member
4 | Admin
5
6type page =
7 | Home
8 | Settings
9
10let canView = (role, page) =>
11 switch (role, page) {
12 | (Guest, Home) => true
13 | (Guest, Settings) => false
14 | (Member, _) => true
15 | (Admin, _) => true
16 }

switch here matches a tuple of two variants. That is useful whenever behavior depends on more than one piece of state at once.

Options instead of null

Missing values use option<'a>, with two cases: Some(value) and None.

1let maybeName: option<string> = Some("Ada")
2let missingName: option<string> = None
3
4let displayName = name =>
5 switch name {
6 | Some(value) => value
7 | None => "Anonymous"
8 }

This changes day-to-day code in a few practical ways:

  • Missing values are explicit in the type, so you can see right away which values need handling.
  • You cannot accidentally read through undefined at runtime. The compiler makes you handle None first.
  • There is one absence model instead of juggling null, undefined, and missing keys.

You will see this often in optional arguments, lookups, and decoded data.

Modules and files

Each file becomes a module. A file named Counter.res exposes its values under Counter.

1/* Counter.res */
2let initial = 0
3let increment = count => count + 1
4
5/* App.res */
6let next = Counter.increment(Counter.initial)

You get namespacing by default, which keeps larger codebases from turning into import and naming sprawl.

Why it's worth it

Once the syntax clicks, the benefits are mostly about reducing ambiguity in the code:

  • You model state directly instead of spreading it across booleans, strings, and nullable fields.
  • Refactors are safer because the compiler shows you every affected branch.
  • option removes a large class of null and undefined bugs.
  • Types are inferred, so the code stays compact.
  • The output still fits naturally into existing JavaScript tooling.

The payoff gets bigger as the codebase grows. The more branches, edge cases, and moving parts you have, the more valuable those guarantees become.

Adding ReScript incrementally

You do not need a rewrite to try it:

  • A JS or TS app can import modules compiled from ReScript.
  • ReScript targets the same runtime, bundler, and npm packages as the rest of your app.
  • You can adopt it one module, feature, or library at a time.

That makes it easy to start with one bounded part of a codebase and expand only if it proves useful.

Keep learning

The official ReScript site covers the full language and toolchain:

Once this page feels familiar, continue with the Quick start, then Signals and Components.

Summary

ReScript facts an agent needs to produce Xote code that compiles on the first try: the syntax that differs from JavaScript/TypeScript, the typing rules that most often cause compile errors, the JS-interop patterns the Xote docs use (@val, @get, @send, @scope, @return(nullable)), and ReScript 12 specifics. Everything here was checked against ReScript 12.2. The rule that matters most: ReScript has no implicit conversions and no null/undefined in normal code; absence is option<'a>, and every conversion is an explicit function call.

Availability

ItemValue
CompilerReScript 12 (rescript npm package); Xote's PPX is built for ReScript 12's ppx ABI
Standard libraryReScript 12 built-in core modules (Array, String, Int, Float, Option, Promise, Dict, Console, Math, Nullable, JSON); @rescript/core is not needed
Commandsnpx rescript (build), npx rescript watch (watch), npx rescript clean, npx rescript format

Rules

  1. Statements need no semicolons; the last expression of a block is its value. let bindings are immutable; mutable state uses ref(x) (read r.contents, write r := v) or mutable record fields.
  2. Functions are (a, b) => body. Labeled arguments are ~name; callers MUST pass them as ~name=value (an unlabeled argument in that position is a compile error: "The argument at this position should be labelled."). Optional labeled arguments are ~name: t=? and arrive as option<t> inside the function; callers pass a plain t (~greeting="Hi") or omit it.
  3. option<'a> (Some(x) / None) replaces null/undefined. JS values that may be null are typed Nullable.t<'a> and converted with Nullable.toOption. The literal null has type nullable<'a>, not option.
  4. Array indexing xs[i] returns option<'a>. Use switch, Option.getOr, or Array.getUnsafe(xs, i) when the index is known to be valid.
  5. Numbers: int and float are distinct. In ReScript 12, + - * / work on both, but both operands MUST have the same type (1 + 2.0 is an error: "You can convert float to int with Float.toInt"). Convert with Int.toFloat, Float.toInt. int division truncates. The float-specific operators +. -. *. /. still exist.
  6. Strings concatenate with ++ (or + in ReScript 12). Non-strings MUST be converted (Int.toString, Float.toString, Float.toFixed(~digits=1)); "n=" ++ 3 is an error. Template strings use backticks: `Hello, ${name}` where name MUST be a string.
  7. Parsing returns options: Int.fromString("42"), Float.fromString("1.5").
  8. Records {id: 1, name: "Ada"} need a declared type; copy-update is {...r, name: "Grace"}. JS objects are a separate type written {"value": string} and accessed with obj["value"].
  9. Variants (type status = Loading | Ready(string)) are matched with switch. A non-exhaustive switch is warning 8, not an error by default: the build succeeds and the missing case throws at runtime. Treat warning 8 as an error.
  10. == is structural equality, === is reference equality. Signals compare with === by default, so a structurally equal new record still notifies.
  11. Pipe: x->f(y) is f(x, y). Xote APIs are designed for -> (count->Signal.get, weather->Resource.value).
  12. Async: let f = async () => …, await inside. An async function returns promise<'a>; using it as 'a is an error with the hint "Did you mean to await this promise before using it?". Promise helpers: Promise.resolve, Promise.thenResolve, Promise.catch, ->ignore to discard.
  13. Exceptions: exception NotFound(string); raise with throw(NotFound("x")) (ReScript 12); catch with try expr catch { | NotFound(_) => … }. JS errors appear as JsExn.
  14. Reserved words cannot be field or prop names: type → type_, for → for_ in Xote JSX (rendered as type/for). React's className is not a prop; use class.
  15. Every .res file is a module named after the file (Counter.res → Counter); a module cannot reference itself by name; submodules are module Name = { … }.
  16. JSX: a component is a module whose make is annotated @xote.component (or @jsx.component); props are make's labeled arguments; one component per module.
  17. Unused values produce warnings, not errors. let _ = expr or expr->ignore discards a value.

Mapping

JavaScript / TypeScriptReScript
const x = 1let x = 1
let x = 1; x = 2let x = ref(1), x := 2, x.contents
null, undefined, x ?? dNone, option, x->Option.getOr(d)
x?.yx->Option.map(v => v.y)
arr[0]arr[0] (returns option), arr->Array.getUnsafe(0)
a === ba === b (reference), a == b (structural)
"a" + 1"a" ++ Int.toString(1)
parseInt(s)Int.fromString(s) (option)
{ ...obj, k: v }{...record, k: v}
obj.prop on untyped JSobj["prop"] with an object type {"prop": t}
async/awaitasync/await
throw new Error(m)throw(Failure(m)) or a custom exception
switch with defaultexhaustive switch, with _ => … as the catch-all case
enum / tagged unionvariant
console.logConsole.log, Console.log2
setTimeout(f, 100)setTimeout(f, 100) via @val external
e.target.value@get external target: Dom.event => {"value": string} = "target" then target(e)["value"]
e.preventDefault()@send external preventDefault: Dom.event => unit = "preventDefault"
document.getElementById(id)@val @scope("document") @return(nullable) external getElementById: string => option<Dom.element> = "getElementById"
JSX className=class=
<input type="text"><input type_="text" />

Patterns

Labeled and optional arguments:

1let greet = (~name: string, ~greeting: option<string>=?) =>
2 greeting->Option.getOr("Hello") ++ ", " ++ name
3
4let a = greet(~name="Ada")
5let b = greet(~name="Ada", ~greeting="Hi")

DOM interop used across the Xote docs:

1@val external setTimeout: (unit => unit, int) => int = "setTimeout"
2@val @scope("window") external innerWidth: int = "innerWidth"
3@get external target: Dom.event => {"value": string} = "target"
4@send external preventDefault: Dom.event => unit = "preventDefault"
5@val @scope("document") @return(nullable)
6external getElementById: string => option<Dom.element> = "getElementById"
7@val external querySelector: string => Nullable.t<Dom.element> = "document.querySelector"
8
9let el: option<Dom.element> = querySelector(".x")->Nullable.toOption

Reading an input's value in a Xote handler:

1let text = Signal.make("")
2
3@xote.component
4let make = () =>
5 <input value={Signal.get(text)} onInput={event => Signal.set(text, target(event)["value"])} />

Async with typed JSON:

1type response
2type user = {id: int, name: string}
3@val external fetch: string => promise<response> = "fetch"
4@send external json: response => promise<user> = "json"
5
6let loadUser = async (id: int) => {
7 let response = await fetch(`/api/users/${Int.toString(id)}`)
8 await json(response)
9}

Variants and exhaustive matching:

1type status = Loading | Ready(string) | Failed(exn)
2
3let label = status =>
4 switch status {
5 | Loading => "…"
6 | Ready(text) => text
7 | Failed(_) => "error"
8 }

Exceptions:

1exception NotFound(string)
2
3let check = id => id > 0 ? id : throw(NotFound("bad id"))
4let safe = try check(-1) catch {
5| NotFound(_) => 0
6}

Anti-patterns

let y = xs[0] + 1 → error This has type: option<int> But it's expected to have type: int → xs[0]->Option.getOr(0) + 1 or Array.getUnsafe.

let n: option<int> = null → error This has type: nullable<'a> → None.

"n=" ++ count with count: int → error string concatenation is expecting: string with the hint You can convert int to string with Int.toString. → "n=" ++ Int.toString(count).

f("x") for let f = (~name) => … → error The argument at this position should be labelled. → f(~name="x").

let z: int = load() for an async function → error This has type: promise<int> → await load() inside an async function, or load()->Promise.thenResolve(…).

switch status { | Loading => … } missing cases → warning 8 You forgot to handle a possible case here and a runtime Match_failure → handle every case.

Edge cases

  • Obj.magic converts any type to any type with no check; use only at JS boundaries, never to silence a type error in Xote code.
  • Externals are not checked against the JS implementation; a wrong external signature compiles and fails at runtime.
  • Object types ({"value": string}) are structural and open to mismatch; records are nominal.
  • Float.toFixed(~digits=1) returns a string and rounds the binary value (273.15 → "273.1").
  • Math.Int.random(min, max) returns an integer in [min, max).

SSR and hydration

Not applicable to the language itself. Note only that module-level code runs at import time, on the server as well as in the browser: do not call DOM externals at module top level in server-rendered apps.

Verify

  • npx rescript exit code 0; read every "We've found a bug for you!" block top to bottom: the first line gives the file and position, then "This has type / But it's expected to have type", then a hint.
  • Treat warning 8 (non-exhaustive match) and warning 26/27 (unused variable, often a mistyped name) as errors.
  • npx rescript format normalises syntax and reveals parse errors.