2016-08-16 697 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