8

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

@Component({
   templateUrl: 'a'
})
export class MyApp {
}
function dummy(component: any) {
     ....
}       
dummay(MyApp);
5
  • Are you trying to pass a class (type) or an instance to dummy? Commented Aug 30, 2018 at 13:19
  • Yes i am passing a class : MyApp. I want to remove any from dummy function and use correct type Commented Aug 30, 2018 at 13:21
  • Have a look at Class decorators in typescriptlang.org/docs/handbook/decorators.html Commented Aug 30, 2018 at 13:25
  • You use the class name as the type for the argument. function dummy(component: MyApp) Commented Aug 30, 2018 at 13:30
  • MyApp can be any class component as it is not usefully. Commented Aug 30, 2018 at 13:32

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Weird that Type in this case comes from Angular and not TypeScript?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.