How can define type of Component in Angular?

Viewed 4707

How can I define the type of Component in a dummy function?

@Component({
   templateUrl: 'a'
})
export class MyApp {
}
function dummy(component: any) {
     ....
}       
dummay(MyApp);
1 Answers

There are a couple of different items in your question that could use clarification.

In your example export class MyApp {...} is creating a class of type MyApp.

Generally you would pass an instance of a class to a function. If that is what you are trying to do, then it would look as follows:

function dummy(component: MyApp) {
     ....
}       
dummay(new MyApp());

If you are actually trying to pass a class type to the function, then you would want to do the following:

import {
  Type
} from '@angular/core';

function dummy(component: Type<any>) {
     ....
}       
dummay(MyApp);

Another way you could make this more powerful is if you restricted the components that could be passed to the function to only those that implement a given interface. An example of this would be as follows:

import {
  Type
} from '@angular/core';

export interface IFoo {
   id: number;
   getStuff: () => string;
}
@Component({
   templateUrl: 'a'
})
export class MyApp implements IFoo {
}
function dummy(component: Type<IFoo>) {
     const stuff = component.getStuff();
     ....
}    

dummay(MyApp);
Related