2016-11-13 61 views
2

的说法,我想写,你解析类的类型(类,不是一个实例),那么该功能将实例基于该参数的实例的功能。描述函数参数以类为打字稿

这是最好的例子来解释:

//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); 

所以我的问题是:什么类型会为“样本”功能帕拉姆是什么?我将如何从函数内部创建一个param实例。

请注意,如果这个问题是重复的,我很抱歉 - 但我不知道这个过程的技术名称,所以很难研究。

回答

3

你希望是这样的。

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

我们知道你有一些类型,它是一个Base。我们将其命名为T,我们会说T extends Base来强制执行此操作。

我们也知道param将构造一个T不带参数。我们可以写new() => T来描述。


基本上去想这种方式是一类既具有实例侧和静态侧(也被称为“构造”的一面)。在你的榜样,BaseFooBar对自己有静的一面。

静态侧为他们每个人的由您指定的所有静态成员(并没有任何在这种情况下),用构建签名一起。在你的情况下,Example需要一个构造函数不需要参数,并产生一些Base的子类型。