HACKER Q&A
📣 raydiatian

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


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?


  👤 satvikpendem Accepted Answer ✓
I use fp-ts with its Either type (like Result in other languages like Rust), works great.

https://gcanti.github.io/fp-ts/


👤 raydiatian
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.

👤 raydiatian
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.

👤 bwestergard
On my team we use Rust-style Result/Option types for any unrecoverable exceptions.

https://github.com/supermacro/neverthrow


👤 schwartzworld
I created my own npm package with a Result type. https://www.npmjs.com/package/schtate

👤 moystard
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.

👤 shams93
catch (e) { const error = e as ; }