Refactor `Result` type
A simple version of this type was introduced to see if we would find it useful (#10361). We've started to use it more widely, so this change adds some ergonomic improvements to make it easier to work with. There are three parts to this, as detailed below.
This keeps the convenience functions ok and error for constructing Result, but it's possible these are no longer necessary as the Ok and Err classes could be constructed directly. An update to this may be considered in a future change.
Note: "Hide whitespace" may be useful for reviewing this change.
kind Becomes ok
The kind property, which was previously of type 'ok' | 'error', has been replaced with an ok property of type boolean. This makes code that checks this property less verbose, and it's similar to the ok property found on the Response type in the Fetch API^1. I believe this was originally suggested by @mxdvl
Before:
if (result.kind === 'ok') {
console.log(result.value);
} else {
console.error(result.error);
}
After:
if (result.ok) {
console.log(result.value);
} else {
console.error(result.error);
}
New Methods
map
Before:
if (result.kind === 'error') {
return result;
}
return doSomething(result.value);
After:
return result.map(doSomething);
flatMap
Before:
if (result.kind === 'error') {
return result;
}
return doSomethingThatCouldFail(result.value);
After:
return result.flatMap(doSomethingThatCouldFail);
mapError
Before:
if (result.kind === 'error') {
return error(`New error message: ${result.error}`);
}
After:
return result.mapError(err => `New error message: ${err}`);
okOrThrow And errorOrThrow Become Methods
Previously these were functions, but they have now become methods alongside the others described above. They've also been renamed to better suit the method approach.
Before:
const value = okOrThrow(doSomething(data), 'Expected this to succeed');
const error = errorOrThrow(
doSomething(data),
'Expected this to fail',
);
After:
const value = doSomething(data).getOrThrow('Expected this to succeed');
const error = doSomething(data).getErrorOrThrow(
'Expected this to fail',
);
I’m definitely partial to an ok, but I first witnessed it in “Error Handling with Result Type” by Jake Trent
Hello :wave:! When you're ready to run Chromatic, please apply the run_chromatic label to this PR.
You will need to reapply the label each time you want to run Chromatic.
Rare @mxdvl sighting 💜
I like the new syntax, it feels a lot more like the syntax I'm used to with Result types in other languages.
Seen on PROD (merged by @JamieB-gu 10 minutes and 8 seconds ago) Please check your changes!