对于这段代码
try {
throw new CustomError();
}
catch (err) {
console.log(err.aPropThatDoesNotExistInCustomError);
}
err
为any
,不会触发类型错误。如何将其缩小到预期错误的类型?
答案 0 :(得分:8)
您需要自己进行检查以缩小catch块内部。编译器不知道或不相信err
肯定是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
}
}
例如,这是CustomError
的恶意实现:
class CustomError extends Error {
constructor() {
super()
throw new Error('Not so fast!'); // The evil part is here
}
aPropThatIndeedExistsInCustomError: string;
}
在这种情况下,err
将不成为CustomError
。我知道,这可能不会发生,但重点是编译器不会自动为您缩小范围。如果您完全确定类型,可以指定另一个变量:
try {
throw new CustomError();
}
catch (_err) {
const err: CustomError = _err;
console.log(err.aPropThatDoesNotExistInCustomError); // errors as desired
}
但请记住,如果您误解了类型,可能会在运行时遇到麻烦。
祝你好运!