How to do try catch and finally statements in TypeScript?

Edit

Typescript 4.0 added the ability to specify unknown and any on catch variables (Issue) And typescript 4.4 added the ability to make unknown the default on catch variables (PR) uning the useUnknownInCatchVariables flag.

With this flag the following is now possible:

catch(e){
    result = e.message; // error under useUnknownInCatchVariables 
    if (typeof e === "string") {
        e.toUpperCase() // works, `e` narrowed to string
    } else if (e instanceof Error) {
        e.message // works, `e` narrowed to Error
    }
}

Specifying arbitrary types on catch variables is still not supported.

Original answer

Typescript does not support annotations on the catch variable. There is a proposal to allow this but it is still being discussed (see here)

Your only solution is to use a type assertion or an extra variable

catch(_e){
    let e:Error= _e;
    result = e.message;
}

catch(e){
    result = (e as Error).message;
}

Unfortunately this will work as well and is completely unchecked:

catch(e){
    result = e.MessageUps;
}

Note

As you can read in the discussion on the proposal, in JS not everything that is thrown has to be an Error instance, so beware of this assumption

Maybe tslint with no-unsafe-any would help catch this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)