TypeScript 函数返回多个选项

BK-*_*BK- 0 javascript observable rxjs typescript es6-promise

我有一个如下功能,我无法理解它。函数如何返回多种类型以及如何使用每种类型?

function(): Observable<Type> | Promise<Type> | Type {
...
}
Run Code Online (Sandbox Code Playgroud)

看起来管道(|)用于指定可以返回多个值。我不明白的是每个什么时候使用?我怀疑是在subscribe发出a时使用了Observable ,默认使用了Promise,在调用函数时使用了直上Type await。

如果我是对的,太好了!我似乎无法找到此功能的文档,以便我可以了解更多信息。你能帮我吗?我怀疑我的问题是我不知道 Google 搜索什么。

更新:附加代码示例

以下是提供多种返回类型的代码示例,但我只返回布尔类型。

@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {

  constructor(private authService: AuthService, private router: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) :
      Observable<boolean> | Promise<boolean> | boolean {
        return this.authService.isAuthenticated()
          .then((authenticated: boolean) => {
            if (authenticated) {
              return true;
            } else {
              this.router.navigate(['/']);
            }
          });
        }

  canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) :
      Observable<boolean> | Promise<boolean> | boolean {
        return this.canActivate(route, state);
      }


}
Run Code Online (Sandbox Code Playgroud)

是什么决定是否按Type原样返回,而不是将其包装在 Promise 或 Observable(用于订阅)中?

mes*_*ill 6

在您的函数体内,您将决定何时返回哪种类型的结果。当您使用返回值时,您并不直接知道结果的类型。因此,您可以cast得到以下结果:

function a(foo: string): string | boolean {
  if (foo) return true
  return "my string value"
}
const b = (a("") as boolean)
const c = (a("hello") as string)
Run Code Online (Sandbox Code Playgroud)

在这种情况下b,typeof booleanwhilec是 a string。