
I'm about to share something that might get me canceled by the JavaScript community: I've stopped throwing errors in TypeScript, and I'm never goin...
For further actions, you may consider blocking this person and/or reporting abuse
Honestly the result & option patterns are the best patterns I’ve seen in so long. They just make more sense but so many people will be stuck in their ways.
they may need lots of byte-sized examples they can copy, absorb and replicate plus a bit of time...
Love it. This is actually a popular/modern practice and has first-class support in several other languages, e.g. C++'s
std::expected
and Rust'sResult
💯Even OCaml which made me love statically-typed languages more. Great post
Yeah i wish it was the default in JS xD
🍿
Yeah, after spending some time with Go/Rust, I've started to use the same pattern in TypeScript. It is generally much more verbose and stable, and for common error types I create a dedicated error handlers, which are type-safe too. Overall, this is really nice solution.
This makes me very grateful for how Rust handles errors. Most of what you just described comes out of the box in Rust.
What if we implement custom errors and throw them, extend basic error? Our custom error can implement the error code and we can still use throw / catch?
Lets take in account the "Problem with throwing" section, and rewrite the code.
The extra benefit is that the errors are checked on class name instead of on a string. This reduces errors by typos.
The main driver in the
Result
solution is that instead of throwing the errors they are returned. So you don't need the type to make the solution happen.