在 TypeScript 中描述将 class 作为参数的函数参数

Describing a function parameter that takes a class as an argument in TypeScript

我想编写一个函数,您可以在其中解析 class 类型(class,而不是实例),然后该函数将根据该参数实例化一个实例。

这最好用例子来解释:

//All possible paramter types must inherit from this base class
class Base { public name : string = ''; }

//These are possible classes that could be parsed to the function
class Foo extends Base { constructor() { super(); console.log("Foo instance created"); } }
class Bar extends Base { constructor() { super(); console.log("Bar instance created"); } }

//This function should take a class that inherits from 'Base' as a paramter - then it will create an instance
function Example(param : ?????????) : Base //I don't know what type the 'param' should be
{
    return new param(); //Create instance?? How do I do this
}

//This should be the output - if it worked (but it doesn't)
Example(Foo); //Logs "Foo instance created""
Example(Bar); //Logs "Foo instance created""

//So if this worked, it would become possible to do this:
let b : Foo = Example(Foo);
let c : Bar = Example(Bar);

所以我的问题是:'Example' 函数的参数是什么类型?我将如何从函数中创建一个参数实例。

请注意,如果这个问题重复,我深表歉意 - 但我不知道这个过程的技术名称,因此很难研究。

你想要这样的东西。

function Example<T extends Base>(param: new () => T): T {
    return new param();
}

我们知道您会有一些类型Base。我们将其命名为 T,我们会说 T extends Base 来强制执行。

我们也知道param会构造一个没有参数的T。我们可以写new () => T来描述。


基本上,考虑这个问题的方法是 class 既有 instance 边,也有 static 边(也称为 "constructor" 侧)。在您的示例中,BaseFooBar 本身具有静态方面。

它们中的每一个的静态端都包含您指定的所有静态成员(在本例中没有任何静态成员),以及构造签名。在你的例子中, Example 接受一个不需要参数的构造函数,并产生 Base.

的一些子类型