Angular 7.2.0:类型“ string”不可分配给类型“ RunGuardsAndResolvers”

时间:2019-03-27 16:41:55

标签: javascript angular typescript angular-router

Angular编译器cli v.7.2.0抛出:

  

属性“ runGuardsAndResolvers”的类型不兼容。类型   不能将'string'分配给'RunGuardsAndResolvers'类型

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

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

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: [
      ...
    ]
  }
];

1 个答案:

答案 0 :(得分:1)

这只是类型推断在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