Dictionary
ReScript has first class support for dictionaries. Dictionaries are mutable objects with string keys, where all values must have the same type. Dicts compile to regular JavaScript objects at runtime.
Create
You can create a new dictionary in a few different ways, depending on your use case.
A few things to note here:
Using the first class
dict{}syntax compiles cleanly to a JavaScript object directlyUsing
Dict.fromArrayis useful when you need to create a dictionary programatically
Copying and merging with spreads
Use ... inside dict{} to copy entries from an existing dictionary into a new one:
You can mix multiple spreads and explicit entries. Entries are applied from left to right: when a key appears more than once, the later value wins. This applies to both explicit entries and entries from a spread:
let defaults = dict{"retries": 3, "timeout": 1000}
let overrides = dict{"timeout": 5000, "retries": 5}
let settings = dict{
...defaults,
"timeout": 2000,
...overrides,
"retries": 1,
}
// The later spread overrides the earlier explicit timeout
Console.log(settings->Dict.get("timeout")) // Some(5000)
// The final explicit entry overrides both spreads
Console.log(settings->Dict.get("retries")) // Some(1)
Spreads do not mutate their source dictionaries. They make a shallow copy: if a value is a mutable object, the new dictionary still refers to that same object. All values in the resulting dictionary must have the same type.
Access
You can access values from a Dictionary either via the the standard library Dict module functions, or using pattern matching.
In the Destructuring example, we're using the
?optional pattern match syntax to pull out theCkey value as an optional, regardless of if the dict has it or not.
Pattern matching
Dictionaries have first class support for pattern matching. Read more in the dedicated guide on pattern matching and destructring in ReScript.
Updating and setting values
You can set and update new values on your dictionary using the Dict.set function. All updates are mutable.
Advanced example: Pattern matching on JSON
JSON objects are represented as dictionaries (dict<JSON.t>). You can leverage that fact to decode JSON in a nice way, using only language features: