Search code examples
angulartypescriptinterface

What is the type of angular 2 components if they are decorated?


I need to have a map of different angular components. This is the map:

  private modals: MapOf<any> = {
    addAttribute: AddAttributeModalComponent,
    editAttribute: EditAttributeModalComponent,
    requestUnit: RequestUnitModalComponent,
    requestAttribute: RequestAttributeModalComponent
  };

As you can see, I have a generic type MapOf. This is it:

export interface MapOf<T> {
  [key: string]: T;
}

Right now I am confused with < any >, because clearly this is a map of components. But I don't know how to set this type and I couldn't find the answer.

ComponentRef doesn't fit here, because it asks for a reference anyway. Type Component doesn't fit also, because my components are decorated and they contain some methods which are not present on 'pure' Component.

Any ideas?


Solution

  • Decorators don't change the type of the class. If you just want to avoid using the type any, have each component class to extend the same abstract class or implement the same interface. Then you can use this new type as the generic one. For example,

    class AddAttributeModalComponent implements MyInterface{...}
    
    MapOf<MyInterface> = {...}
    

    The other option to try would be to create a new union type:

    type MyNewType = AddAttributeModalComponent | 
                     EditAttributeModalComponent |
                     RequestUnitModalComponent |
                     RequestAttributeModalComponent;
    
    MapOf<MyNewType> = {...};