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);
console.log(err.aPropThatDoesNotExistInCustomError);
} else {
console.log(err);
}
}
For example, here is my evil implementation CustomError:
class CustomError extends Error {
constructor() {
super()
throw new Error('Not so fast!');
}
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);
}
, , .
!
PS: . TypeScript # 8677 # 9999 .