【问题标题】:Is it possible to extract the instance type from the instantiable type?是否可以从可实例化类型中提取实例类型?
【发布时间】:2022-08-10 21:24:58
【问题描述】:
class ClassOne {
  property1 = true;
}

type Instantiable = { new(...args: any[]): ClassOne };

是否可以直接从Instantiable 类型中提取ClassOne?如果是这样,那怎么办?

    标签: typescript


    【解决方案1】:

    TypeScript 提供了一个名为 InstanceType 的实用程序类型。你可以像这样使用它:

    class ClassOne {
      property1 = true;
    }
    
    type Instantiable = { new(...args: any[]): ClassOne };
    
    type T = InstanceType<Instantiable>;
    

    TypeScript Playground

    在后台,它在条件类型中使用 infer 关键字:

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

    进一步阅读

    【讨论】:

      猜你喜欢
      • 2011-07-31
      • 2012-01-07
      • 2018-05-26
      • 2011-11-05
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多