4 ms·
Ask HN: 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?
- raydiatian 4y agoI 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.
- TechBro8615 4y agoYou might like fp-ts and its Result type.
- shams93 4y agocatch (e) { const error = e as <Your custom error type>; }
- raydiatian 4y agoOn 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.
- bwestergard 4y agoOn my team we use Rust-style Result/Option types for any unrecoverable exceptions. https://github.com/supermacro/neverthrow https://github.com/supermacro/neverthrow
- satvikpendem 4y agoI use fp-ts with its Either type (like Result in other languages like Rust), works great. https://gcanti.github.io/fp-ts/ https://gcanti.github.io/fp-ts/
- raydiatian 4y agoHad 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.
- schwartzworld 4y agoI created my own npm package with a Result type. https://www.npmjs.com/package/schtate https://www.npmjs.com/package/schtate
- moystard 4y agoI 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.