Switching Back to Exceptions in TypeScript

2024-06-03 · Ryan X. Charles

I previously wrote about how I was using Rust-like Result types in TypeScript as a better way to handle errors (1, 2). However, I’ve decided to switch back to using exceptions in TypeScript to reduce the total amount of code.

TypeScript, like JavaScript, propagates errors with exceptions. This is fine, except that there is no way to know if a function can throw an exception without reading the source code or the documentation. The compiler doesn’t help you at all. So because I was implementing everything in Rust simultaneously, I decided to use Result types in TypeScript as well.

Unfortunately, this led to very verbose code. With exceptions, unhandled errors are propagated automatically. But with Result, you have to check for errors and then propagate them by hand. This made every single line of code that handles an error into about five lines of code. In Rust, this is not an issue, because Rust provides the ? operator to make this easy. But TypeScript doesn’t have this operator, so you have to write a lot of code to propagate errors. By switching back to exceptions, I can significantly reduce the amount of code I have to write to handle errors, and the result is more readable.

I’ve also decided to switch from using the Option enum back to using TypeScript’s ? operator instead (which has a completely different meaning than in Rust). The TypeScript version is much more concise and idiomatic.

All this means the earthbucks-opt-res package is now deprecated.


Earlier Blog Posts


Back to Blog

Home · About · Blog · Privacy · Terms
X · Telegram · Discord · reddit · GitHub
Copyright © 2024 Ryan X. Charles LLC