DEV Community

Discussion on: Type-Safe Error Handling In TypeScript

Collapse
 
patroza profile image
Patrick Roza

The only thing I don’t like is that this brings us back to callbacks, which so elegantly got rid of with await.

Collapse
 
stealthmusic profile image
Jan Wedel

Would be great if typescript allows pattern matching, then you’ll do

with(result){
   Err(e) => console.log(“error!”);
   Ok(value) => console.log(value);
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kip13 profile image
kip

Rust flavor here

Thread Thread
 
stealthmusic profile image
Jan Wedel

Yes, that's nice. There are a couple of functional languages that support it. E.g. Erlang where I first saw this in action.

Collapse
 
_gdelgado profile image
Gio

Maybe one day!

Thread Thread
 
stealthmusic profile image
Jan Wedel

Actually you can do something similar:

blog.logrocket.com/pattern-matchin...

It’s not as pretty as real pattern matching but it fits to this use car.

Collapse
 
impurist profile image
Steven Holloway
Collapse
 
patroza profile image
Patrick Roza • Edited

One way I was able to deal with 'callback hell':

  • Add functional helpers like map, mapErr, biMap (match), flatMap (andThen) etc that can work with both Result... and Promise<Result...
  • Add .pipe function on Ok and Err, and Promise, pretty much as implemented in rxjs: accept to pass N amount of continuation functions with signature: (previous) => next

so now I can:

await getSomeRecordsAsync() // => Promise<Result<SomeRecords, SomeError[]>>
  .pipe(
    map(someRecords => someRecords.map(x => x.someField).join(", ")), // => Promise<Result<string, SomeError[]>>
    mapErr(err => err.map(x => x.message).join(", ")), // => Promise<Result<string, string>>
    flatMap(saveStringAsync), // => Promise<Result<void, someError>>
    // etc
  )

(with full Typescript typing support btw!)

Thinking about releasing it to GitHub and npm at some point :)

Collapse
 
patroza profile image
Patrick Roza

My post, framework and sample just landed dev.to/patroza/result-composition-...