Why Catch clause variable type annotation must be any?

Typescript doesn’t let you do that because there’s no way that typescript can verify at compile time that the only thing the code can throw is a ValidationError. For that matter, you don’t know that either: what if you get a RangeError, because the maximum call stack has been exceeded? Obviously that’s unlikely (you’d have to build up a big call stack before calling this), but nothing about this code can guarantee that it won’t happen.

If you want the error to have a certain type, you will need to either add code to verify that it is actually that type:

catch (err: unknown) {
  if (err instanceof ValidationError) {
     // Inside this block, err is known to be a ValidationError
  }
}

Or you will need to use type assertions to tell typescript “i know it’s this type, trust me”:

catch (err: unknown) {
  getValidationErrors(err as ValidationError);
}
// or:
catch (err: unknown) {
  const knownError = err as ValidationError;
  getValidationERrors(knownError);
}

This is just so commom in Java or other languages…

Different languages have different constraints on their designs. For example, in Java you can define which errors your function will throw as part of the function definition, as in

public static FileInputStream example(String fileName) throws FileNotFoundException {

Neither javascript nor typescript have a way to specify this in a function definition.

And java lets you have multiple catch blocks, with different types of errors being handled by different ones, but since typescript only exists at compile time, that’s not an option. Everything must be handled in a single catch block, and distinguishing which type of error you’re dealing with must be done with explicit code.

Leave a Comment

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