2016-08-16 702 views
1

在以下Typescript代碼片段中,dialogComponent的類型聲明的含義是什麼? (發自https://www.lucidchart.com/techblog/2016/07/19/building-angular-2-components-on-the-fly-a-dialog-box-example)。Typescript函數聲明使用new()

我發現下面的問題是擴展了迄今收到的答案:How to create a new object from type parameter in generic class in typescript?

+0

我想這意味着函數'createDialog'有有方法'新的()',沒有什麼特別的對象參數。 –

+0

這意味着'dialogComponent'是一個具有不帶參數並返回'DialogComponent'的構造函數的類型。這很可能可以通過'createDialog(dialogComponent:typeof DialogComponent)'完成。 – 2016-08-16 03:41:08

+0

它看起來像「{new():DialogComponent}」應該是dialogComponent參數的類型聲明,但將'new()'用作對象鍵是沒有意義的。我不確定它應該做什麼,但在plunker demo([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關鍵字被稱爲對象,這些對象的類。

這是廣泛應用於lib.d.ts,例如ArrayConstructor

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

當使用泛型創建的打字稿工廠,有必要通過自己的構造函數來引用類類型。因此,不要使用類型:T,請使用類型:{new():T;}

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

更多詳細信息在here