首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Promises & TypeScript

Promises & TypeScript
EN

Stack Overflow用户
提问于 2018-11-20 22:57:17
回答 1查看 128关注 0票数 1

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

代码语言:javascript
复制
isAuthenticated(path: string): boolean

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

代码语言:javascript
复制
isAuthenticated(path: string): boolean {

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

但是该方法给出了一个错误/警告,如下所示:

代码语言:javascript
复制
A function whose type is neither declared type is neither 'void' nor 'any' must return a value
EN

回答 1

Stack Overflow用户

发布于 2018-11-20 23:01:50

您不会从isAuthenticated返回任何内容。你也不能在这里“等待”简单的结果。

您可以这样做:

代码语言:javascript
复制
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中执行任何其他操作,则可以将代码简化为:

代码语言:javascript
复制
isAuthenticated(path: string): Promise<boolean> {
  return this.authorization.isAuthenticated();
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53395729

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档