过去 3 年我一直在做 Swift 开发,最近切换到打字稿。在 Swift 中,NSError 类型的错误为我们提供了一些属性。在 JavaScript 中,任何错误都是错误的。为什么有任何错误?如何创建具有某些属性的自定义类并在整个项目中使用它?try { const decodedResult = decode(token) // Adding userId in the headers to use in the models. req.headers.userId = decodedResult.paylod.id next()} catch (error) { console.log(error) new errorController(401, 'Authentication required.', res)}现在这里的错误对象是 any 类型。我希望它是强类型的。
3 回答

犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
那是因为您可以throw在 Javascript 中执行任何操作:
throw 1;
由于任何深度嵌套的代码都可能在某处抛出某些内容,因此 Typescript 不可能正确键入它,这就是“错误”具有any类型的原因。
然而,Typeguards 可以帮助您缩小特定的错误类型:
class CustomError extends Error {
constructor(code: number, message: string) {
super(message);
this.code = code;
}
}
try {
throw new CustomError(404, "Not Found");
} catch(error) {
if(!(error instanceof CustomError))
throw error;
console.log(error.code); // correctly typed here
}
添加回答
举报
0/150
提交
取消