We’d like to introduce a feature we’ve been experimenting with recently - automatic optional chaining.
Automatic optional chaining is similar to optional chaining in TypeScript (someVal?.someField?.otherField?.something
), but with a twist - because of ReScript’s type system, we can do the optional chaining automatically without the developer needing to indicate where to unwrap options.
Let’s explain how this works with an example:
type thing = {something: option<int>}
type otherRecord = {thing: option<thing>}
type targetRecord = {otherRecord: option<otherRecord>}
let x: targetRecord = ...
// Today you'll need to do something like this:
// option<int>
let something = switch x {
| {otherRecord: Some({thing: Some({something: Some(something)}) }) } => Some(something)
| _ => None
}
// How you could do it with automatic optional chaining:
// option<int>
let something = x.otherRecord.thing.something
Notice how there’s no unwrapping of each optional level, neither via switching nor with ?
- you tell which value you want to access via dot access, and the compiler will help you get there without the need of manual plumbing (unwrapping each optional level yourself). This also means options in the chain will be automatically flattened.
Rationale
Our reasoning for this feature can be summarized roughly like this:
You know what deeply nested optional value you’re after accessing. Getting there is just manual plumbing. Thanks to the type system, the compiler can do that unwrapping automatically for you.
It’s also a purely additive feature. You can continue switching at any level of the optional value chain if you want. This is a first, exploratory step in seeing how we can ease working with optionals. We’re intentionally starting small, only focusing on solving easy access of deeply nested optional data (via records).
Editor integration
This will be fully integrated with the editor extension, meaning autocomplete will also automatically unwrap options. This will hopefully make the feature feel natural. Most users will probably not even notice they’re using automatic optional chaining.
Testing
You can test this yourself by locally installing the prebuilt ReScript npm package from here. If you want to test how it feels with proper editor extension integration (highly recommended), download and install this vsix
.
Feedback
We’re looking for your general feedback and comments on this feature. Test it, and let us know how it feels. Whether it makes sense directly, or if it’s confusing. And so on.
We look forward to hearing your thoughts and feedback! More exploration in this space will follow.