"错误"类型中不存在属性"代码"

J-Y*_*Yen 4 firebase typescript angularfire2 angular

我如何访问Error.code属性?我得到一个Typescript错误,因为属性'code'在'Error'类型上不存在.

this.authCtrl.login(user, {
   provider: AuthProviders.Password,
   method: AuthMethods.Password
}).then((authData) => {
    //Success
}).catch((error) => {
   console.log(error); // I see a code property
   console.log(error.code); //error
})
Run Code Online (Sandbox Code Playgroud)

或者有另一种方法来制作自定义错误消息吗?我想用另一种语言显示错误.

小智 15

真正的问题是Node.js定义文件没有导出正确的错误定义.它使用以下内容进行错误(并且不导出此内容):

interface Error {
    stack?: string;
}
Run Code Online (Sandbox Code Playgroud)

它导出的实际定义是在NodeJS名称空间中:

export interface ErrnoException extends Error {
    errno?: number;
    code?: string;
    path?: string;
    syscall?: string;
    stack?: string;
}
Run Code Online (Sandbox Code Playgroud)

所以下面的类型转换会起作用:

.catch((error: NodeJS.ErrnoException) => {
    console.log(error);
    console.log(error.code);
})
Run Code Online (Sandbox Code Playgroud)

这似乎是Node定义中的一个缺陷,因为它与新的Error()实际包含的对象不一致.TypeScript将强制执行接口错误定义.

  • 不是一个完整的解决方案。完整的解决方案还将显示需要添加的导入语句,以便“拥有”“NodeJS”符号。 (9认同)
  • @SzczepanHołyszewski 这个答案对我来说非常有用,不需要额外的“导入”。 (4认同)

koe*_*ech 5

您必须将类型从 catch ie 转换为错误参数

.catch((error:any) => {
    console.log(error);
    console.log(error.code);
});
Run Code Online (Sandbox Code Playgroud)

或者您可以通过这种方式直接访问代码属性

.catch((error) => {
    console.log(error);
    console.log(error['code']);
});
Run Code Online (Sandbox Code Playgroud)