createUserWithEmailAndPassword和firebase.auth.Error处理catch给出编译错误TS2345

时间:2016-11-17 16:26:42

标签: typescript firebase firebase-authentication

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

的代码

Methode描述: (方法)firebase.auth.Auth.createUserWithEmailAndPassword(email:string,password:string):firebase.Promise

在当时的工作中指定firebase.auth.Auth,但firebase.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);

                });

1 个答案:

答案 0 :(得分:2)

如果您查看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>; 的签名:

firebase.auth.Error

这就是为什么你看到TypeScript报告错误的原因:你不能传递一个接收code的箭头函数,因为它包含一个Error不属于的Error属性出现在firebase.auth.Error

您可以将收到的code转发给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); }); ,以便您可以访问其var slideSource = document.getElementById('slideSource'); document.getElementById('handle').onclick = function(){ if(!document.getElementById('Ad-Detect-js')){ slideSource.className = slideSource.className ? 'fade' : 'fade'; } }属性,而不会产生TypeScript错误:

div#slideSource {
opacity:1;
transition: opacity 1s; 
display: block;
    margin-bottom: 30px;
    padding: 20px 10px;
    background: #D30000;
    text-align: center;
    font-weight: bold;
    color: #fff;
    border-radius: 5px;
}

div#slideSource.fade {
opacity:0;
}

另外,您并不需要为箭头函数中的参数指定类型,因为TypeScript会推断它们。事实上,这就是错误首先发生的原因。