2016-11-17 39 views
1

當我調用下面的方法,我想趕上錯誤,並檢查錯誤代碼,我不能指定錯誤類型以外的錯誤類型,所以我無法訪問該錯誤。代碼來自firebase.auth.ErrorcreateUserWithEmailAndPassword和處理捕獲與firebase.auth.Error給編譯錯誤TS2345

了Methode描述: (方法)firebase.auth.Auth.createUserWithEmailAndPassword(電子郵件:字符串,密碼:字符串):firebase.Promise

Specifing 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); 

       }); 
+0

看起來你的'error'變量是'Error'類型的,你需要'firebase.auth.Error' –

回答

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的箭頭函數,因爲它包含Error中不存在的code屬性。

,就可以把收到的Errorfirebase.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); 
    }); 

而且,你並不真的需要指定類型的參數因爲TypeScript會推斷它們。事實上,這就是爲什麼錯誤首先受到影響的原因。