2016-11-13 5 views
2

クラスの型(クラスではなくインスタンス)を解析し、そのパラメータに基づいてインスタンスをインスタンス化する関数を記述したいと思います。TypeScriptの引数としてクラスを取る関数のパラメータを記述する

これが最良の例で説明されています

//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はどのようになるかのタイプ?そして、どのようにして関数内からparamのインスタンスを作成しますか?

この質問が重複している場合、私はお詫び申し上げますが、このプロセスの技術名称はわからないので、調査するのは難しいです。

答えて

3

このようなものが必要です。

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

私たちは、あなたがBaseある何らかのタイプを持っているだろうことを知っています。私たちはそれをTと名付けようとしており、それを強制するにはT extends Baseと言います。

paramは、パラメータなしでTを構成することも知っています。これを記述するにはnew() => Tと書くことができます。


基本的にこれを考えるための方法は、クラスは(も「コンストラクタ」側と呼ばれる)インスタンス側と静的側の両方を持っているということです。あなたの例では、Base,Foo、およびBarは静的な面があります。

それぞれの静的側は、指定したすべての静的メンバー(この場合は何もありません)と構成シグネチャで構成されます。あなたのケースでは、Exampleはコンストラクタが引数を必要とせず、Baseというサブタイプを生成します。

関連する問題