2017-07-28 80 views
2

对于这一段代码缩减错误类型中捕获

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

errany和不触发类型错误。它如何被缩小到错误预期的类型?

回答

2

您需要自行检查一下,以便在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; 
} 

在这种情况下errCustomError 。我知道,这可能不会发生,但问题是编译器不会为您自动缩小范围。如果你是绝对肯定的类型,你可以分配到另一个变量:

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

但要记住,你可能在运行时遇到麻烦,如果你是错误的类型。

祝你好运!

P.S .:有关更多信息,请参阅TypeScript问题#8677#9999

+0

谢谢。 'instanceof'在这里不是问题,错误类型是明确的,而且它是'CustomError'类型,不一定是实例。 'const err:CustomError = _err'看起来像一个非常丑陋的黑客。我检查了#8677和#9999,看起来他们是通过PR关闭的,但我不确定PR如何解决问题, – estus

+0

我不明白'instanceof'的含义。如果您执行'抛出新的CustomError()',则已创建(并抛出)'CustomError'类的新实例。当且仅当'err'的构造函数是'CustomError'构造函数时,'err instanceof CustomError'才会返回'true'。 – jcalz

+0

它曾经是因为你甚至无法用'instanceof'或其他类型的警卫来缩小范围(所以你几乎*已经*将捕获的对象分配给一个新的变窄的变量),但#9999修复了它的一部分。 – jcalz