title | description | canonical |
---|---|---|
Newcomer Examples |
Quick examples for users new to ReScript |
/docs/manual/latest/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
<CodeTab labels={["ReScript", "JS Output"]}>
let possiblyNullValue1 = None
let possiblyNullValue2 = Some("Hello")
switch possiblyNullValue2 {
| None => Console.log("Nothing to see here.")
| Some(message) => Console.log(message)
}
var possiblyNullValue1;
var possiblyNullValue2 = "Hello";
if (possiblyNullValue2 !== undefined) {
console.log(possiblyNullValue2);
} else {
console.log("Nothing to see here.");
}
<CodeTab labels={["ReScript", "JS Output"]}>
type universityStudent = {gpa: float}
type response<'studentType> = {
status: int,
student: 'studentType,
}
// Empty output
<CodeTab labels={["ReScript", "JS Output"]}>
let student1 = {
"name": "John",
"age": 30,
}
var student1 = {
name: "John",
age: 30,
};
Or using record:
<CodeTab labels={["ReScript", "JS Output"]}>
type payload = {
name: string,
age: int,
}
let student1 = {
name: "John",
age: 30,
}
var student1 = {
name: "John",
age: 30,
};
See here.
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 Nullable
module. In this case, toOption
:
<CodeTab labels={["ReScript", "JS Output"]}>
let greetByName = (possiblyNullName) => {
let optionName = Nullable.toOption(possiblyNullName)
switch optionName {
| None => "Hi"
| Some(name) => "Hello " ++ name
}
}
function greetByName(possiblyNullName) {
if (possiblyNullName == null) {
return "Hi";
} else {
return "Hello " + possiblyNullName;
}
}
This check compiles to possiblyNullName == null
in JS, so checks for the presence of null
or undefined
.