处理typescript中的catch语句

时间:2016-11-26 20:14:58

标签: typescript

在我的下面的代码中,af是firebase对象,它进行http调用。 我试图抓住错误。下面的代码工作正常。

this.af.auth.login({
        email: formData.value.email,
        password: formData.value.password
      }).then(
          (success) => {console.log(success);}
      ).catch(
          (err: any) => {
            if (err.code.includes('user-not-found')) {
              this.error = "User not found. Invalid username/password";
            }
          }
      );

错误是如下的对象:

 err {
  code: 'auth/user-not-found',
  message: 'this user was not found'
 }

为了给它一个类型我定义了一个接口如下:

interface Error {
  code: string;
  message: string;
}

并更改了catch语句,如下所示:

  .catch((err: Error) => ...

但是,typescript会抛出错误:

 typescript: src/pages/login/login.ts, line: 35 
            Argument of type '(err: Error) => void' is not assignable to parameter of type '(a: Error) => any'. Types of 
            parameters 'err' and 'a' are incompatible. Type 'Error' is not assignable to type 'Error'. Property 'code' 
            is missing in type 'Error'. 

      L34:  ).catch(
      L35:      (err: Error) => {
      L36:        if (err.code.inc

0 个答案:

没有答案