jbo*_*boo 1 firebase typescript firebase-authentication
当我调用以下方法并想捕获错误并检查错误代码时,我无法指定错误类型以外的错误类型,因此无法访问错误。代码来自firebase.auth.Error.
方法描述:(方法)firebase.auth.Auth.createUserWithEmailAndPassword(email: string, password: string): firebase.Promise
Specifingfirebase.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'.
Run Code Online (Sandbox Code Playgroud)
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);
});
Run Code Online (Sandbox Code Playgroud)
如果您查看firebase.d.ts,您将看到createUserWithEmailAndPassword具有以下签名:
createUserWithEmailAndPassword(email: string, password: string): firebase.Promise<any>;
Run Code Online (Sandbox Code Playgroud)
并firebase.Promise扩展firebase.Promise_Instance具有以下签名catch:
catch(onReject?: (a: Error) => any): firebase.Thenable<any>;
Run Code Online (Sandbox Code Playgroud)
这就是为什么你看到一个错误报告打字稿:你不能将接收一个箭头的功能firebase.auth.Error,如包含code这不存在财产Error。
您可以将接收Error到的转换为 afirebase.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);
});
Run Code Online (Sandbox Code Playgroud)
此外,您实际上不需要为箭头函数中的参数指定类型,因为 TypeScript 会推断它们。事实上,这就是错误首先被影响的原因。
| 归档时间: |
|
| 查看次数: |
3056 次 |
| 最近记录: |