gpt4 book ai didi

angular - 为什么 Angular 类型 "Routes"是可变的?

转载 作者:行者123 更新时间:2023-12-04 03:35:13 25 4
gpt4 key购买 nike

我想让传递给 Angular Routerroutes 成为常量,这样我就可以对所有可能的路由路径使用 IntelliSense:

const route = [
{ path: 'my-path', component: MenuItemsComponent },
{ path: 'my-path', component: MenuItemsComponent },
] as const;
const myRoutes = route as Routes;

Typescript 说我不能这样做,它会抛出这个错误:

Conversion of type 'readonly [{ readonly path: "my-path"; readonly component: typeof MenuItemsComponent; }, { readonly path: "my-path"; readonly component: typeof MenuItemsComponent; }]' to type 'Routes' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.
The type 'readonly [{ readonly path: "my-path"; readonly component: typeof MenuItemsComponent; }, { readonly path: "my-path"; readonly component: typeof MenuItemsComponent; }]' is 'readonly' and cannot be assigned to the mutable type 'Routes'.

但为什么 Routes 是可变类型?我无法理解。

编辑

解释为什么我需要 const,是因为在 const 中我们可以做到这一点:

type Path = typeof route[number]['path'];

所以现在我可以将变量限制为在路由器中声明的路径。

最佳答案

我在我的本地做了一个快速测试,你的代码在 Angular 11 上编译得很好。

如果您真正关心的是在您的 IDE 中自动完成;然后你可以尝试转换,像这样:

const route: routes = [
{ path: 'my-path', component: MenuItemsComponent } as Route,
{ path: 'my-path', component: MenuItemsComponent } as Route,
] as const;

我在 IntelliJ 中获得了自动完成功能:

enter image description here

另一种选择可能是创建您自己的类来扩展 Route 接口(interface),并使用它来创建您自己的 Route 接口(interface)。

一般是这样的:

export class MyRouteClass extends Route {
path?: string
pathMatch?: string
matcher?: UrlMatcher
component?: Type<any>
redirectTo?: string
outlet?: string
canActivate?: any[]
canActivateChild?: any[]
canDeactivate?: any[]
canLoad?: any[]
data?: Data
resolve?: ResolveData
children?: Routes
loadChildren?: LoadChildren
runGuardsAndResolvers?: RunGuardsAndResolvers
}

然后:

const route: routes = [
Object.assign(new MyRouteClass(), { path: 'my-path', component: MenuItemsComponent }),
Object.assign(new MyRouteClass(), { path: 'my-path', component: MenuItemsComponent }),
];

关于angular - 为什么 Angular 类型 "Routes"是可变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67037808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com