文档 / 语言手册 / Newcomer Examples
Edit

You are currently looking at the v6.0 - v8.2 docs (Reason v3.6 syntax edition). You can find the latest manual page here.

(These docs are equivalent to the old BuckleScript docs before the ReScript rebrand)

Newcomer Examples

An example is worth a thousand words.

This section is dedicated to newcomers trying to figure out general idioms & conventions. If you're a beginner who's got a good idea for an example, please suggest an edit!

Use the option type

Reason (Old Syntax)ML (Older Syntax)JS Output
let possiblyNullValue1 = None;
let possiblyNullValue2 = Some("Hello");

switch (possiblyNullValue2) {
| None => Js.log("Nothing to see here.")
| Some(message) => Js.log(message)
};

Create a Parametrized Type

Reason (Old Syntax)ML (Older Syntax)JS Output
type universityStudent = {gpa: float};

type response('studentType) = {
  status: int,
  student: 'studentType,
};

Creating a JS Object

Reason (Old Syntax)ML (Older Syntax)JS Output
let student1 = {
  "name": "John",
  "age": 30,
};

Or using record:

Reason (Old Syntax)ML (Older Syntax)JS Output
type payload = {
  name: string,
  age: int,
};

let student1 = {
  name: "John",
  age: 30,
};

Modeling a JS Module with Default Export

See here.

Checking for JS nullable types using the option type

For a function whose argument is passed a JavaScript value that's potentially null or undefined, it's idiomatic to convert it to an option. The conversion is done through the helper functions in ReScript's Js.Nullable module. In this case, toOption:

Reason (Old Syntax)ML (Older Syntax)JS Output
let greetByName = (possiblyNullName) => {
  let optionName = Js.Nullable.toOption(possiblyNullName);
  switch (optionName) {
  | None => "Hi"
  | Some(name) => "Hello " ++ name
  }
};

This check compiles to possiblyNullName == null in JS, so checks for the presence of null or undefined.