【问题标题】:How would I type an object that contains a class/constructor?如何键入包含类/构造函数的对象?
【发布时间】:2022-08-11 04:34:11
【问题描述】:

使用 Typescript 类装饰器时遇到问题,但为简单起见,我的示例不会包含它们

class AClass {
    handle() {
       console.log(\"Handled\")
    }
}

function callHandler(constructor: Type) {
   return new constructor().handle()
}

callHandler(AClass)

我尝试用Function 替换Type,但我得到:

file:ln:rw - error TS2351: This expression is not constructable.
  Type \'Function\' has no construct signatures.

ln             new constructor().handle()
                   ~~~~~~~~~~~~~~~

除了any,还有什么我可以使用的类型被认为是可构造的?

    标签: node.js typescript class


    【解决方案1】:

    其实,我读过Typescript/#17572 并且能够找到类型

    type Abstract<T> = Function & {prototype: T};
    type Constructor<T> = new (...args: any[]) => T;
    type Class<T> = Abstract<T> | Constructor<T>;
    

    Class&lt;{ handle: () =&gt; void }&gt; 为我的代码工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-02-25
      • 1970-01-01
      • 2010-12-21
      • 1970-01-01
      相关资源
      最近更新 更多