Angular 型组件

标签 angular typescript type-safety

我有一个routesList我在 Angular 的 app-routing.module 中使用 routesList 的类型是:

type routesList = {
  [key: string]: {
    path: string;
    title: string;
    component: Type<Component>;
  };
};

当前导出的列表是:

export const routesList: routesList = {
  home: {
    path: '',
    title: 'Curation Console',
    component: AppComponent,
  },
  otherpage: {
    path: 'otherpage',
    title: 'Other Page',
    component: OtherPageComponent,
  },
};

但我收到 component: AppComponent 的错误说

typescript: Type of 'typeof AppComponent' is not assignable to type 'Type<Component>'.
Type 'AppComponent' has no properties in common with type 'Component'.

Type<Component>此用途不正确? 还有其他方法可以获取 Angular 组件的类型吗?

最佳答案

Robby 详细介绍了如何/为何 Type<any>就能解决问题。这是另一种方法。

而是定义您自己的类型,类似于 Route (@ Angular/路由器)类型。使用现有的Route界面。

type routesList = {
  [key: string]: Route
};

type routerList = Record<string, Route>;

关于 Angular 型组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75680342/

相关文章:

angular - *ngIf <ng-content> 是否可以从外部获取任何内容?

angular - 在 Ionic 2 App 的构造函数之前首先加载模板

javascript - Angular 看不到我组件的选择器

html - Angular Flickity 改变元素

typescript - 允许子类使用函数属性或方法覆盖

java - 从返回的接口(interface)进行转换?总是安全吗?

javascript - 从 Angular 4 将数据发布到 Firebase

angular - 依赖注入(inject)如何只注入(inject)部分参数?

scala - Scala 中具有依赖类型的参数的模式匹配的类型安全性

c++ - 如何在 cppcheck 或 clang 中检查类型安全?