Skip to content

Commit f9543da

Browse files
MeAkibcrisbeto
authored andcommitted
docs: type the external redirect guard (#33887)
`externalRedirect()` passed its guard to `canActivate` as an inline arrow function. `canActivate` accepts `CanActivateFn` as well as the deprecated class-based guards, typed as `ProviderToken<any>`. Any function also matches `ProviderToken<any>`, so TypeScript didn't check the inline guard against `CanActivateFn`. For example, a guard returning a number would still compile. This declares the guard as a `CanActivateFn` before passing it to `canActivate`, so its return value is type checked. The behavior is unchanged. A comment explains why the type is needed, so it isn't inlined again later. (cherry picked from commit 1543543)
1 parent 8a2ffd1 commit f9543da

1 file changed

Lines changed: 9 additions & 7 deletions

File tree

‎docs/src/app/routes.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
*/
88

99
import {Component} from '@angular/core';
10-
import {Route, Routes} from '@angular/router';
10+
import {CanActivateFn, Route, Routes} from '@angular/router';
1111
import {canActivateComponentSidenav} from './pages/component-sidenav/component-sidenav-can-load-guard';
1212

1313
@Component({template: ''})
@@ -95,14 +95,16 @@ function adevRedirect(path: string) {
9595
}
9696

9797
function externalRedirect(target: string | (() => string)): Partial<Route> {
98+
// Typed explicitly, because `canActivate` also accepts deprecated class-based guards. Any function
99+
// matches that type as well, so an inline guard wouldn't have its return value type checked.
100+
const redirect: CanActivateFn = () => {
101+
window.location.href = typeof target === 'string' ? target : target();
102+
return false;
103+
};
104+
98105
return {
99106
// The router requires a `component`.
100107
component: RedirectPlaceholder,
101-
canActivate: [
102-
() => {
103-
window.location.href = typeof target === 'string' ? target : target();
104-
return false;
105-
},
106-
],
108+
canActivate: [redirect],
107109
};
108110
}

0 commit comments

Comments
 (0)