You are currently looking at the v11.0 docs, which are still a work in progress. If you miss anything, you may find it in the older v10.0 docs here.
Object
ReScript objects are like records, but:
No type declaration needed.
Structural and more polymorphic, unlike records.
Doesn't support updates unless the object comes from the JS side.
Doesn't support pattern matching.
Although ReScript records compile to clean JavaScript objects, ReScript objects are a better candidate for emulating/binding to JS objects, as you'll see.
Type Declaration
Optional, unlike for records. The type of an object is inferred from the value, so you never really need to write down its type definition. Nevertheless, here's its type declaration syntax:
Visually similar to record type's syntax, with the field names quoted.
Creation
To create a new object:
Note: as said above, unlike for record, this me
value does not try to find a conforming type declaration with the field "age"
and "name"
; rather, the type of me
is inferred as {"age": int, "name": string}
. This is convenient, but also means this code passes type checking without errors:
Since the type checker doesn't try to match me
with the type person
. If you ever want to force an object value to be of a predeclared object type, just annotate the value:
RESlet me: person = {
"age": "hello!"
}
Now the type system will error properly.
Access
Update
Disallowed unless the object is a binding that comes from the JavaScript side. In that case, use =
Combine Types
You can spread one object type definition into another using ...
:
This only works with object types, not object values!
Tips & Tricks
Since objects don't require type declarations, and since ReScript infers all the types for you, you get to very quickly and easily (and dangerously) bind to any JavaScript API. Check the JS output tab:
// The type of document is just some random type 'a
// that we won't bother to specify
@val external document: 'a = "document"
// call a method
document["addEventListener"](. "mouseup", _event => {
Js.log("clicked!")
})
// get a property
let loc = document["location"]
// set a property
document["location"]["href"] = "rescript-lang.org"
The external
feature and the usage of this trick are also documented in the external section later. It's an excellent way to start writing some ReScript code without worrying about whether bindings to a particular library exists.