缩小捕获中的错误类型
Narrowing down error type in catch
对于这段代码
try {
throw new CustomError();
}
catch (err) {
console.log(err.aPropThatDoesNotExistInCustomError);
}
err
是 any
并且不会触发类型错误。如何将错误缩小到预期的错误类型?
您需要自己执行检查以缩小 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
}
但请记住,如果您弄错了类型,您可能 运行 会在 运行 时遇到麻烦。
祝你好运!
对于这段代码
try {
throw new CustomError();
}
catch (err) {
console.log(err.aPropThatDoesNotExistInCustomError);
}
err
是 any
并且不会触发类型错误。如何将错误缩小到预期的错误类型?
您需要自己执行检查以缩小 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
}
但请记住,如果您弄错了类型,您可能 运行 会在 运行 时遇到麻烦。
祝你好运!