承诺和TypeScript

时间:2018-11-20 14:57:17

标签: typescript promise angular6

我有一个必须通过抽象类实现的方法,该类具有如下签名:

isAuthenticated(path: string): boolean

在实现中,我正在调用来自授权服务器的承诺

isAuthenticated(path: string): boolean {

this.authorization.isAuthenticated().then((res) => {
    if(res == true) {
      return true;
    }
    return false;
});
}

但是该方法给我这样的错误/警告:

A function whose type is neither declared type is neither 'void' nor 'any' must return a value

1 个答案:

答案 0 :(得分:1)

您没有从isAuthenticated返回任何信息。您也不能只是在这里“等待”简单的结果。

您可以这样做:

isAuthenticated(path: string): Promise<boolean> {
  // return the ".then" to return a promise of the type returned
  // in the .then
  return this.authorization.isAuthenticated().then((res) => {
    if(res === true) {
      return true;
    }
    return false;
  });
}

并允许调用方“等待”布尔结果。

注意:假设this.authorization.isAuthenticated返回一个Promise<boolean>,而您不需要在.then中执行任何其他操作,则代码可以简化为:

isAuthenticated(path: string): Promise<boolean> {
  return this.authorization.isAuthenticated();
}