typescript - 承诺和打字稿
问题描述
我有一个必须通过抽象类实现的方法,它的签名如下:
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
解决方案
您没有从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();
}
推荐阅读
- sql - 将同一表中的一列中的值更新为 SQL Server 中的另一列
- ios - 在 iOS 13 及更高版本中,当应用程序被杀死时,launchoptions 在单击删除通知时重新调整 nil
- c++ - 错误无法将“float*”转换为“float”作为回报
- laravel - 将 Laravel Test 7 和 Laravel Passport 9.3 与 Personal Access Client 一起使用会出现异常“尝试获取非对象的属性 'id'”
- amazon-web-services - AWS DMS 源数据库事务边界
- mysql - 如何使用 MYSQL 在最终表中包含所有列的默认值为 0 的缺失行?
- kubernetes-ingress - 有和没有主机的入口
- javascript - 我可以在 Javascript 中设置一个二维数组作为键吗?
- python - Python 初学者 ML 项目问题
- sql - 当您将多条记录包装在 VALUES 子句中的括号中时,SQL 是否将多条记录视为一条记录?