gpt4 book ai didi

javascript - Angular 7.2.0 : Type 'string' is not assignable to type 'RunGuardsAndResolvers'

转载 作者:行者123 更新时间:2023-11-30 14:05:57 37 4
gpt4 key购买 nike

Angular compiler-cli v.7.2.0 正在抛出:

Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers'

在导入到 AppRoutingModule 的常量中设置 runGuardsAndResolvers: 'always' 时。

当我在 AppRoutingModule 本身中设置 runGuardsAndResolvers: 'always' 时,这不会发生。

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { adminRouterConfig } from 'src/app/core/_routing/admin-router-config';

const appRoutes: Routes = [
{ path: '', component: HomeComponent },
{
path: '',
children: [
...adminRouterConfig
]
},
{ path: '**', redirectTo: '', pathMatch: 'full' }
];

@NgModule({
imports: [RouterModule.forRoot(appRoutes,
{ enableTracing: true }
)],
exports: [RouterModule]
})

export class AppRoutingModule { }

admin-router-config.ts

import { AuthGuard } from 'src/app/core/_guards/auth.guard';

export const adminRouterConfig = [
{
path: 'admin',
runGuardsAndResolvers: 'always',
canActivate: [AuthGuard],
children: [
...
]
}
];

最佳答案

这正是类型推断在 TypeScript 中的工作方式。当您第一次将它分配给一个变量时,它会将变量的类型推断为 {runGuardsAndResolvers: string} ,然后在以后使用时不匹配。在这种情况下,您必须明确指定类型:

const options = {
runGuardsAndResolvers: "always" as RunGuardsAndResolvers
};

看看这个例子:

const method = (options: { runGuardsAndResolvers: RunGuardsAndResolvers }) => {
return options;
};

// This works
method({ runGuardsAndResolvers: "always" });

// This fails
const options = { runGuardsAndResolvers: "always" };
method(options);

// This works
const typedOptions = {
runGuardsAndResolvers: "always" as RunGuardsAndResolvers
};
method(typedOptions);

现场演示:

Edit Typescript type inference

关于javascript - Angular 7.2.0 : Type 'string' is not assignable to type 'RunGuardsAndResolvers' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55382410/

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