Learning ReScript
A quick tour of ReScript syntax, with examples and links to the official docs for deeper study.
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 | Guest3 | SignedIn(string)4 | Banned(string)56let 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 userdeclares a variant — a closed set of cases. The compiler knows every valueusercan hold.switchmatches each case directly. Add a new case touserlater (say,Suspended), and the compiler points out everyswitchthat 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
greetingdoes 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 = 12let add = (a, b) => a + b34let 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}56type status =7 | Idle8 | Saving9 | Failed(string)1011let 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 | Guest3 | Member4 | Admin56type page =7 | Home8 | Settings910let canView = (role, page) =>11 switch (role, page) {12 | (Guest, Home) => true13 | (Guest, Settings) => false14 | (Member, _) => true15 | (Admin, _) => true16 }
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> = None34let displayName = name =>5 switch name {6 | Some(value) => value7 | 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
undefinedat runtime. The compiler makes you handleNonefirst. - 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 = 03let increment = count => count + 145/* 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.
optionremoves a large class ofnullandundefinedbugs.- 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
| Item | Value |
|---|---|
| Compiler | ReScript 12 (rescript npm package); Xote's PPX is built for ReScript 12's ppx ABI |
| Standard library | ReScript 12 built-in core modules (Array, String, Int, Float, Option, Promise, Dict, Console, Math, Nullable, JSON); @rescript/core is not needed |
| Commands | npx rescript (build), npx rescript watch (watch), npx rescript clean, npx rescript format |
Rules
- Statements need no semicolons; the last expression of a block is its value.
letbindings are immutable; mutable state usesref(x)(readr.contents, writer := v) ormutablerecord fields. - 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 asoption<t>inside the function; callers pass a plaint(~greeting="Hi") or omit it. option<'a>(Some(x)/None) replacesnull/undefined. JS values that may benullare typedNullable.t<'a>and converted withNullable.toOption. The literalnullhas typenullable<'a>, notoption.- Array indexing
xs[i]returnsoption<'a>. Useswitch,Option.getOr, orArray.getUnsafe(xs, i)when the index is known to be valid. - Numbers:
intandfloatare distinct. In ReScript 12,+ - * /work on both, but both operands MUST have the same type (1 + 2.0is an error: "You can convert float to int with Float.toInt"). Convert withInt.toFloat,Float.toInt.intdivision truncates. The float-specific operators+. -. *. /.still exist. - Strings concatenate with
++(or+in ReScript 12). Non-strings MUST be converted (Int.toString,Float.toString,Float.toFixed(~digits=1));"n=" ++ 3is an error. Template strings use backticks:`Hello, ${name}`wherenameMUST be a string. - Parsing returns options:
Int.fromString("42"),Float.fromString("1.5"). - 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 withobj["value"]. - Variants (
type status = Loading | Ready(string)) are matched withswitch. A non-exhaustiveswitchis warning 8, not an error by default: the build succeeds and the missing case throws at runtime. Treat warning 8 as an error. ==is structural equality,===is reference equality. Signals compare with===by default, so a structurally equal new record still notifies.- Pipe:
x->f(y)isf(x, y). Xote APIs are designed for->(count->Signal.get,weather->Resource.value). - Async:
let f = async () => …,awaitinside. Anasyncfunction returnspromise<'a>; using it as'ais an error with the hint "Did you mean to await this promise before using it?". Promise helpers:Promise.resolve,Promise.thenResolve,Promise.catch,->ignoreto discard. - Exceptions:
exception NotFound(string); raise withthrow(NotFound("x"))(ReScript 12); catch withtry expr catch { | NotFound(_) => … }. JS errors appear asJsExn. - Reserved words cannot be field or prop names:
type→type_,for→for_in Xote JSX (rendered astype/for). React'sclassNameis not a prop; useclass. - Every
.resfile is a module named after the file (Counter.res→Counter); a module cannot reference itself by name; submodules aremodule Name = { … }. - JSX: a component is a module whose
makeis annotated@xote.component(or@jsx.component); props aremake's labeled arguments; one component per module. - Unused values produce warnings, not errors.
let _ = exprorexpr->ignorediscards a value.
Mapping
| JavaScript / TypeScript | ReScript |
|---|---|
const x = 1 | let x = 1 |
let x = 1; x = 2 | let x = ref(1), x := 2, x.contents |
null, undefined, x ?? d | None, option, x->Option.getOr(d) |
x?.y | x->Option.map(v => v.y) |
arr[0] | arr[0] (returns option), arr->Array.getUnsafe(0) |
a === b | a === 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 JS | obj["prop"] with an object type {"prop": t} |
async/await | async/await |
throw new Error(m) | throw(Failure(m)) or a custom exception |
switch with default | exhaustive switch, with _ => … as the catch-all case |
enum / tagged union | variant |
console.log | Console.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") ++ ", " ++ name34let 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"89let el: option<Dom.element> = querySelector(".x")->Nullable.toOption
Reading an input's value in a Xote handler:
1let text = Signal.make("")23@xote.component4let make = () =>5 <input value={Signal.get(text)} onInput={event => Signal.set(text, target(event)["value"])} />
Async with typed JSON:
1type response2type user = {id: int, name: string}3@val external fetch: string => promise<response> = "fetch"4@send external json: response => promise<user> = "json"56let 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)23let label = status =>4 switch status {5 | Loading => "…"6 | Ready(text) => text7 | Failed(_) => "error"8 }
Exceptions:
1exception NotFound(string)23let check = id => id > 0 ? id : throw(NotFound("bad id"))4let safe = try check(-1) catch {5| NotFound(_) => 06}
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.magicconverts 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 rescriptexit 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 formatnormalises syntax and reveals parse errors.
Related
/docs/quick-start— project setup and Xote-specific compile errors./docs/learn/components— components, props, children./docs/guides/forms— event interop for inputs.- Official docs: https://rescript-lang.org/docs/manual/latest/introduction