Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Avoid Catching Errors with TypeScript 2.5 Optional Catch Clauses


    Typescript 2.5 has brought a couple of interesting changes to the table. let's take a look at these new features and how to take advantage of these features.

    Optional catch clauses: TypeScript 2.5 brings a new ECMAScript-bound feature for making catch clauses optional. Most of the time, you’ll find yourself writing a try/catch but not really caring about the thrown error. So Typescript provides you some syntactic sugar for omitting the error paramter.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Let's start by installing TypeScript globally. Make sure that you install the specific version 2.5. Let's close terminal, and make sure that our work space is set to TypeScript version 2.5.2.

    Now, let us write a try block. In this try block, we'll try to pass a faulty JSON. Now, let's write a catch block. For this, we'll pass in ERR as a parameter that will be an error, and then we'll log error.message into our console.

    We'll run our TypeScript file using ts-node. Ts-node is a handy plugin that allows you to compile and run TypeScript files directly from the console. If we run this, we can see that the error message is printed for the faulty JSON and dispatched from the try block to the catch block.

    The new feature, called as the option catch clause, added in TypeScript 2.5, allows us to omit this error parameter altogether. If you remove the error parameter, starting from TypeScript 2.5, this code will compile without any issues. Let's write a log that we are inside the catch block, and then we can go ahead and do something else.

    The advantage that this feature provides us is that we need not carry forward the error from the try block, especially if you're not doing any error handling inside the catch block.

    If you go ahead and run this in our ts-node, you can see that it runs without any issues, and logs that we are inside the catch block. We can also verify the same by running our TypeScript compiler on our file, and it will compile without any issues.

    If we go ahead and open our compiled JavaScript file, you can see the catch block has been modified to accommodate the error. As you can see, TypeScript isn't doing anything magic, in other words. It's just adding a syntactic sugar that omits the error parameter when it's not necessary.

    If we go back and inspect our TypeScript file, you can notice that TypeScript achieves this syntactic sugar by restricting us to access the error only when it's declared.