2016-08-16 11 views
1

dialogComponentの型宣言の意味は、次のTypescriptコードスニペットではどのような意味ですか?Typescript関数宣言でnew()が使用されます

createDialog(dialogComponent: { new(): DialogComponent }) : 
    Promise<ComponentRef<DialogComponent>> { ... } 

https://www.lucidchart.com/techblog/2016/07/19/building-angular-2-components-on-the-fly-a-dialog-box-exampleから)。 How to create a new object from type parameter in generic class in typescript?

+0

私はそれが 'createDialog'メソッド')( '新しい、何も特別なを持っているオブジェクト引数を持っている機能を意味推測。 –

+0

これは、 'dialogComponent'は、パラメータを取らず、' DialogComponent'を返すコンストラクタを持つ型であることを意味します。 'createDialog(dialogComponent:typeof DialogComponent)'によっても同じことが達成される可能性があります。 –

+0

'{new():DialogComponent}'はdialogComponentパラメータの型宣言であると思われますが、 'new()'をオブジェクトキーとして使用するのは意味がありません。私はそれが何をやろうとしているのか分かりませんが、大胆なデモ([link](https://plnkr.co/edit/GmOUPtXYpzaY81qJjbHp?p=preview))では、 'new()'をランダムなテキストに置き換えました。すべてがエラーなしで以前と同じように動作していたので、実際には何もしません。 – ABabin

答えて

1

あなたの例では、dialogComponentは実際のクラスであり、インスタンスではありません。言い換えれば、クラスのコンストラクタ関数です。
はここでの例です:あなたが見ることができるように

interface A {} 

class A1 implements A {} 
class A2 implements A {} 

function factory(ctor: { new(): A }): A { 
    return new ctor(); 
} 

let a1 = factory(A1); // type of a1 is A 
let a2 = factory(A2); // type of a2 is A 

は、factory機能はnewキーワードを使用して呼び出すことができるオブジェクトを期待し、そしてそのようなオブジェクトはクラスです。

これは広く例えばArrayConstructorlib.d.tsに使用されます。

interface ArrayConstructor { 
    new (arrayLength?: number): any[]; 
    new <T>(arrayLength: number): T[]; 
    new <T>(...items: T[]): T[]; 
    (arrayLength?: number): any[]; 
    <T>(arrayLength: number): T[]; 
    <T>(...items: T[]): T[]; 
    isArray(arg: any): arg is Array<any>; 
    readonly prototype: Array<any>; 
} 
2

ジェネリックを使用して活字体で工場を作る、彼らのコンストラクタ関数でクラス型を参照する必要がある:

は、私がこれまでに受け取った回答に展開し、次の質問を見つけました。したがって、 タイプの代わりに:タイプを使用してください:{new():T;}

function create<T>(c: {new(): T; }): T { 
    return new c(); 
} 

詳細はhereです。

関連する問題