【问题标题】:Typescript how to export type of class that is returned from class factoryTypescript如何导出从类工厂返回的类的类型
【发布时间】:2021-01-04 06:07:33
【问题描述】:

我有一个返回类的函数。类在函数中定义,定义取决于函数的输入。我正在使用 typescript mixins 。我创建了一个typescript playground,清楚地表明了这个问题。

function MIXIN1<TBase extends Mixin1Dependencies>(Base: TBase){
  return class MIXIN1Class extends (Base as Mixin1Dependencies){
    constructor(props: any){
      super(props);
      console.log('MXIN1');  
    }
  }
}
type Mixin2Dependencies = MixinDependencies<Origin & MIXIN1Class>;

我正在尝试在Mixin2Dependencies 的定义中使用MIXIN1Class 类型定义。有没有办法暴露内部 MIXIN1Class ?或实现类似的行为,我曾尝试将 implements 与单独的接口一起使用,但变得非常多余。

【问题讨论】:

  • MIXIN1 是一个类工厂。它的返回类型取决于每次调用它时作为TBase 传递的类型参数。

标签: typescript typescript-typings


【解决方案1】:

我认为您正在寻找的是 ReturnType 实用程序类型。

尝试ReturnType&lt;typeof MIXIN1&gt;,这应该会导致您的示例中的MIXIN1Class

https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype

【讨论】:

  • ReturnType&lt;MIXIN1&gt; 错误:'MIXIN1' 指的是一个值,但在这里被用作一个类型。您的意思是“typeof MIXIN1”吗​​?
  • @kevzettler 你试过ReturnType&lt;typeof MIXIN1&gt;吗?
  • @spender 是的,我相信这是对一般问题的正确答案,但它在 MIXIN 实现中引发了许多其他错误
  • @spender 是的,对,将typeof 添加到原始答案中,谢谢
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 2021-04-05
相关资源
最近更新 更多