使用 TypeScript 声明类类型(将类作为参数传递) [英] Declare class type with TypeScript (pass class as parameter)

查看:55
本文介绍了使用 TypeScript 声明类类型(将类作为参数传递)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个接受不同构造函数的函数,如下所示:

so I have a function which accepts different constructors, like so:

export class SomeSuperClass {
 ...
}

export class A extends SomeSuperClass {
 ...
}

export class B extends SomeSuperClass {
 ...
}


const foo = function(Clazz: SomeSuperClass){

  const v = new Clazz();

}

foo(A);  // pass the class itself
foo(B);  // pass the class itself

问题是 SomeSuperClass 意味着 Clazz 将是 SomeSuperClass 的实例,而不是 SomeSuperClass 本身.

the problem is that SomeSuperClass means that Clazz will be an instance of SomeSuperClass, but not SomeSuperClass itself.

我试过这样的蠢事(这显然行不通):

I tried something stupid like this (which obviously doesn't work):

   const foo = function(Clazz: SomeSuperClass.constructor){

      const v = new Clazz();

   }

这样做的正确方法是什么?

what's the right way to do this?

推荐答案

正如您所提到的,您正在寻找的是如何描述类构造函数而不是实例.可以通过以下方式实现:

As you mentioned, what you are looking to is how to describe class constructor and not the instance. It can be achieved by:

const foo = function(ctor: new() => SomeSuperClass) {
    ...
}

或者(在这种情况下结果相同):

Or alternatively (same result in this case):

const foo = function(ctor: typeof SomeSuperClass) {
    ...
}

这也要求 AB 具有无参数构造函数

This also requires A and B to have parameterless constructors

这篇关于使用 TypeScript 声明类类型(将类作为参数传递)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆