Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 519
ross Avatar asked Oct 16 '25 01:10

ross


2 Answers

The type used for a component in a Route by Angular is Type<any>, so defining your routesList as follows should be OK:

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

If you want to narrow that down to a custom base class you're using for your components (e.g. Type<MyComponentBase>), you can, but Component is not that base class. It's an interface that is used as a decorator to mark components as components, and your own component classes almost certainly do not conform to that interface.

Instead of defining your own routesList type, it's probably better to just use the one provided by Angular, and extend that one if needed.

like image 88
Robby Cornelissen Avatar answered Oct 18 '25 17:10

Robby Cornelissen


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>;
like image 22
Pankaj Parkar Avatar answered Oct 18 '25 19:10

Pankaj Parkar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!