【问题标题】:createUserWithEmailAndPassword and handling catch with firebase.auth.Error give compilation error TS2345createUserWithEmailAndPassword 并使用 firebase.auth.Error 处理 catch 给出编译错误 TS2345
【发布时间】:2017-04-01 07:13:21
【问题描述】:

当我调用以下方法并且我想捕获错误并检查错误代码时,我无法指定错误类型以外的错误类型,因此我无法访问错误。来自firebase.auth.Error的代码。

方法说明: (方法) firebase.auth.Auth.createUserWithEmailAndPassword(email: string, password: string): firebase.Promise

在 then 工作中指定 firebase.auth.Authfirebase.auth.Error 给我一个编译错误。

error TS2345: Argument of type '(error: Error) => void' is not assignable to parameter of type '(a: Error) => any'.
Types of parameters 'error' and 'a' are incompatible.
Type 'Error' is not assignable to type 'firebase.auth.Error'.
Property 'code' is missing in type 'Error'.

 

this.auth.createUserWithEmailAndPassword(username, password)
                .then( (auth: firebase.auth.Auth) => { return auth; } )
                .catch( (error: firebase.auth.Error) => {

                    let errorCode = error.code;
                    let errorMessage = error.message;

                    if (errorMessage === "auth/weak-password") {
                    alert("The password is too weak.");
                    } else {
                    alert(errorMessage);
                    }
                    console.log(error);

                });

【问题讨论】:

  • 看起来你的error 变量是Error 类型,你需要firebase.auth.Error

标签: typescript firebase firebase-authentication


【解决方案1】:

如果你查看firebase.d.ts,你会看到createUserWithEmailAndPassword有这个签名:

createUserWithEmailAndPassword(email: string, password: string): firebase.Promise<any>;

firebase.Promise 扩展了firebase.Promise_Instance,它具有catch 的签名:

catch(onReject?: (a: Error) => any): firebase.Thenable<any>;

这就是您看到 TypeScript 报告错误的原因:您无法传递接收firebase.auth.Error 的箭头函数,因为它包含code 属性,而Error 中不存在该属性。

您可以将收到的Error 转换为firebase.auth.Error,这样您就可以访问它的code 属性,而不会影响TypeScript 错误:

this.auth.createUserWithEmailAndPassword(username, password)
  .then((auth: firebase.auth.Auth) => { return auth; } )
  .catch((error: Error) => {

    let authError = error as firebase.auth.Error;
    let errorCode = authError.code;
    let errorMessage = authError.message;

    if (errorMessage === "auth/weak-password") {
      alert("The password is too weak.");
    } else {
      alert(errorMessage);
    }
    console.log(error);
  });

此外,您实际上不需要为箭头函数中的参数指定类型,因为 TypeScript 会推断它们。事实上,这就是错误首先受到影响的原因。

【讨论】:

    猜你喜欢
    • 2016-08-21
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多