【问题标题】:How to give exact type-information in return type without using "any" for a function that returns multiple different types?对于返回多种不同类型的函数,如何在不使用“任何”的情况下在返回类型中给出准确的类型信息?
【发布时间】:2019-08-13 16:59:35
【问题描述】:

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

我尝试设置多个类型,如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 在这里很好。

谢谢!

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

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

    组件工厂解析器会更喜欢这个:)

    【讨论】:

      【解决方案2】:

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

      然后您现在可以将您的函数修改为如下所示。

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

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

      【讨论】:

      • 这就是我已经尝试过的,但没有奏效。请参阅接受的答案,据我了解,它是基于组件工厂解析器的实现,它是 Angular 特定的。无论如何,谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2012-09-19
      • 2016-08-03
      • 2022-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多