user3873278
user3873278

Reputation:

How to give exact type-information in return type without using "any" for a function that returns multiple different types?

In my typescript-code I have a function that returns a component based on the navigation-type that has been set by the user, so I can display the component to the user. At the moment the function returns "any" and I am wondering on how to give it exact return types?

I have tried to set multiple types like Type1 | Type2, but it does not work and shows errors.

  private createEditContainer(entry: any) {
    const component = this.getListComponentByNavType();
    this.editContainer.clear();
    const factory = this.resolver.resolveComponentFactory(component);
    this.editComponentRef = this.editContainer.createComponent(factory);
    this.editComponentRef.instance.entry = entry;
  }

  private getListComponentByNavType(): any {   // I want this "any" to be actual types
    switch (this.navtype) {
      case TaskdefinitionNavTypes.TYPE:
        return TaskdefinitionListComponent;
      case TaskdefinitionNavTypes.ENUMS:
        return SingleSelectListComponent;
    }
  }

I want to return actual types and not any. Or maybe an explanation on why any is fine here.

Thank you!

Upvotes: 1

Views: 54

Answers (2)

Sodimu Segun Michael
Sodimu Segun Michael

Reputation: 117

You need to declare the types for the return type in the declaration file or check if the package came with its own type.

Then you can now modify your function to look like this.

 private getListComponentByNavType(): TaskdefinitionListComponent | SingleSelectListComponent {  
switch (this.navtype) {
  case TaskdefinitionNavTypes.TYPE:
    return TaskdefinitionListComponent;
  case TaskdefinitionNavTypes.ENUMS:
    return SingleSelectListComponent;
}

This should solve your problem. }

Upvotes: 0

Poul Kruijt
Poul Kruijt

Reputation: 71901

For this instance you have to use Type<T>, this will change your function typing to:

private getListComponentByNavType(): Type<TaskdefinitionListComponent | SingleSelectListComponent> {}

The component factory resolver will like that better :)

Upvotes: 0

Related Questions