【问题标题】:Infer constructor type in TypeScript在 TypeScript 中推断构造函数类型
【发布时间】:2019-04-26 20:05:48
【问题描述】:

是否可以在 TypeScript 中推断类的构造函数类型? 我试过了,但它似乎不起作用:

type Constructor<K> = K extends { new: infer T } ? T : any;

【问题讨论】:

  • 怎么样:type Constructor&lt;K&gt; = K extends { new: () =&gt; infer T } ? T : any;
  • class Foo {}, type CtorOfFoo = typeof Foo
  • 您可以编辑此内容以显示您要完成的工作的minimal reproducible example 吗?

标签: typescript conditional-types


【解决方案1】:

您可以像这样通过构造函数引用类类型,而不是试图推断它吗?

type Constructor<K> = { new(): K };

const x: Constructor<String> = String; 

const s = new x();

【讨论】:

    【解决方案2】:

    已经有一个预定义的条件类型允许您从一个类类型中提取实例类型,称为InstanceType

    class A { private x: any}
    
    type AInstance = InstanceType<typeof A> // same as A
    

    这个类型的定义是:

    type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;
    

    【讨论】:

    • 看起来很有趣,但不幸的是,我需要它。
    • @MarkusMauch 不清楚您的意思,您需要根据实例类型获取类类型吗?不要认为可以从实例类型访问信息
    • 是的,这是一个 known issue 类实例没有强类型 constructor 属性。因此,除非您只想获得Function,否则您可能会被new (...args: any) =&gt; T 卡住,除非您手动加强您关心的所有类的constructor 属性。
    猜你喜欢
    • 2019-09-03
    • 1970-01-01
    • 2022-01-26
    • 2019-02-07
    • 2019-09-23
    • 1970-01-01
    • 2021-05-30
    • 2020-10-17
    相关资源
    最近更新 更多