I'm struggling to understand a function that returns multiple types. How does each type get used?
function(): Observable<Type> | Promise<Type> | Type {
...
}
The pipe (|) seems to indicate that the function can return various values. But I'm confused about when to use each type. My guess is that Observables are for subscriptions, Promises are default, and raw Types are for await calls.
I've scoured for documentation on this feature but can't find much. Can anyone provide insight? I feel stuck because I don't know what to search for.
UPDATE: More Code to Consider
Here's an example with multiple return types, though only boolean is returned.
@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);
}
}
What influences the decision to return the Type
directly versus wrapping it in a Promise or Observable for subscriptions?