Typescript 如何在返回类型中提供准确的类型信息而不使用;任何;对于返回多个不同类型的函数?

Typescript 如何在返回类型中提供准确的类型信息而不使用;任何;对于返回多个不同类型的函数?,typescript,Typescript,在我的typescript代码中,我有一个函数,它根据用户设置的导航类型返回一个组件,因此我可以向用户显示该组件。目前,函数返回“any”,我想知道如何给出确切的返回类型 我尝试设置多个类型,如Type1 | Type2,但它不起作用并显示错误 private createEditContainer(entry: any) { const component = this.getListComponentByNavType(); this.editContainer.clea

在我的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


谢谢大家!

对于此实例,您必须使用
类型
,这会将您的函数类型更改为:

private getListComponentByNavType(): Type<TaskdefinitionListComponent | SingleSelectListComponent> {}
私有getListComponentByNavType():类型{}

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

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

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

 private getListComponentByNavType(): TaskdefinitionListComponent | SingleSelectListComponent {  
switch (this.navtype) {
  case TaskdefinitionNavTypes.TYPE:
    return TaskdefinitionListComponent;
  case TaskdefinitionNavTypes.ENUMS:
    return SingleSelectListComponent;
}
这应该能解决你的问题。
}

我已经试过了,但没用。请参阅已接受的答案,据我所知,它基于组件工厂解析器的实现,这是特定于角度的。无论如何谢谢你!