3 ms·
Reminds me of a pattern I've wished would take off in TS, but hasn't (yet): const result = await fetchData().catch(e => e) if (_.isError(result)) {
by rattray 6y ago
Reminds me of a pattern I've wished would take off in TS, but hasn't (yet):
const result = await fetchData().catch(e => e)
if (_.isError(result)) {
return "some failure"
}
return (await result.json()).foo
TS is smart enough to know whether result will be of type Error or the Response type.
This pattern should replace most Either cases when the left is an error state of some kind. Also should replace exceptions and promise rejections.
You can also analogously replace a Maybe type with nullability, simply `type MaybeFoo = Foo | null`.
- tym0 6y agoI agree with Maybe not being that useful in TS but the point of an Either/Result type is that the caller is gonna handle it each branch differently. In your example the caller has no way to tell the difference between an error and the succesful return value.
- rattray 6y agoPerhaps I was unclear, the implicit typing is so: const result: FetchResult | Error = ... if (_.isError(result)) { // Here TS knows that result is of type Error return } // Here TS knows that result is of type FetchResult On my phone, apologies for shorthand In any case, with this pattern TS can easily tell the difference between success and error (or left and right or whatever) as long as the error / left case is a class of a different type than the success / right case. Tldr, where relevant, classes are cleaner than tagged disjoint unions in TS. Errors are one situation where this is relevant.
- mcintyre1994 6y agoI’ve seen and used the Maybe version of this a few times, I really like this Typescript feature. Using it for errors is clever :)