Search code examples
angulartypescripttype-safety

Angular type of Components


I have a routesList that I use in the app-routing.module of Angular The type of the routesList is:

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

The current list that is being exported is:

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

But I'm getting an error for component: AppComponent saying

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

Is the Type<Component> incorrect for this use? Is there another way I could get the type of Angular Components?


Solution

  • Robby had covers the details of how/why Type<any> would solve the problem. Here is another way of doing it.

    Instead defining your own type similar to Route(@angular/router) type. Use the existing Route interface.

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

    type routerList = Record<string, Route>;