如何在不使用“ any”的情况下为返回多个不同类型的函数提供确切的返回类型信息?

时间:2019-08-13 08:34:14

标签: typescript

在我的打字稿代码中,我有一个函数可以根据用户设置的导航类型返回组件,因此可以向用户显示该组件。目前,该函数返回“ any”,我想知道如何为它指定确切的返回类型?

我尝试设置多种类型,例如Type1 | Type2,但它不起作用并显示错误。

  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;
    }
  }

我想返回实际类型,而不是any。或许可以解释一下为什么any很好。

谢谢!

2 个答案:

答案 0 :(得分:1)

对于这种情况,您必须使用Type<T>,这会将您的函数键入更改为:

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

组件工厂解析器会更好:)

答案 1 :(得分:0)

您需要在声明文件中声明返回类型的类型,或者检查包是否带有其自己的类型。

然后,您现在可以修改函数,使其看起来像这样。

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

这应该可以解决您的问题。   }