Ask HN: What is the “proper” way to do error-handling in TypeScript?

2 points by raydiatian ↗ HN
Folks, I feel like I'm losing my mind. Typescript's concept that `error` is either `any` or `unknown` feels like such a massive gaping problem. I get that it's Javascript's fault for not having a rigorous error typing system. What are some strategies you guys use to expose the kinds of errors your libs throw, or capture the errors other people's code throws?

9 comments

[ 2.2 ms ] story [ 42.9 ms ] thread
I have already considered using Errors in return type unions, that is

    function getIntOrFailMiserably(): number | Error {
      ..
    }
Is that really the best there is? Obviously, I can't control OPC (other people's code. you down with OPC? yeah you know me) with this, unless I wrap it and search like a hawk for the error.
You might like fp-ts and its Result type.
catch (e) { const error = e as <Your custom error type>; }
On an aside, how do you feel about this? Typescript was supposed to bring type visibility to JavaScript. But this still feels like bring your own research. If you input the wrong <Your custom error type>, TS compiler won’t prompt you. This makes me sad.
Had a chat with some of the `typescript` discord folks. Apparently the accepted belief is that “all exceptions are treated as unchecked and there’s not much buyin that exposing the thrown error types add value. Basically it’s “bring your own research” to handing errors, or configure a default catcher.
I usually use the unknown type and leverage type guards for isolating the exact type and processing it. If it falls down the type guards, process as generic error.