How to strongly type try/catch blocks in TypeScript

Vlad Gheorghita
Geek Culture
Published in
4 min readAug 18, 2021

--

Oops

Unfortunately Javascript does not support multiple catch(error) to allow you to run a different code based on the error type. But, there are ways we can improve error handling in our single catch statement to leverage the power of classes and the instanceof operator. Lets see an example of catching different exceptions in a language such as C#.

Good ol’ classic C# try/catch

The above example is awesome! We don’t have to do any manual type checking on the exception, we don’t have any if statements to make our code less readable and it also gives us the ability to extract the different bits of code in each catch statement in its own function and reuse it in other try/catch blocks. Perfect!

Now lets see a typical try/catch block in TypeScript.

--

--

Vlad Gheorghita
Geek Culture

And the Internet said: let there be web development. Find me on twitter @browsepedia