首页 > 解决方案 > 承诺和打字稿

问题描述

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

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

标签: typescriptpromiseangular6

解决方案


您没有从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返回 aPromise<boolean>并且您不需要在 中执行任何其他操作.then,则代码可以简化为:

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

推荐阅读