Catch Error Type Limit

For this piece of code

try {
  throw new CustomError();
}
catch (err) {
  console.log(err.aPropThatDoesNotExistInCustomError);
}

err- anyand does not cause type errors. How can it be narrowed down to the type in which an error is expected?

+4
source share
1 answer

You need to do a check to narrow down inside the catch block. The compiler does not know and does not believe that errit will definitely be CustomError:

try {
  throw new CustomError();
}
catch (err) {
  console.log('bing');
  if (err instanceof CustomError) {
    console.log(err.aPropThatIndeedExistsInCustomError); //works
    console.log(err.aPropThatDoesNotExistInCustomError); //error as expected
  } else {
    console.log(err); // this could still happen
  }
}

For example, here is my evil implementation CustomError:

class CustomError extends Error {
  constructor() {
    super()
    throw new Error('Not so fast!');  // The evil part is here
  }
  aPropThatIndeedExistsInCustomError: string;
}

In this case errit will not CustomError. I know that this probably will not happen, but the fact is that the compiler will not do this automatically for you. If you are absolutely sure of the type, you can assign another variable:

try {
  throw new CustomError();
}
catch (_err) {
  const err: CustomError = _err;
  console.log(err.aPropThatDoesNotExistInCustomError); // errors as desired
}

, , .

!

PS: . TypeScript # 8677 # 9999 .

+4

Source: https://habr.com/ru/post/1682522/


All Articles