簡體   English   中英

Typescript函數聲明使用new()

[英]Typescript function declaration uses new()

以下Typescript代碼片段中dialogComponent的類型聲明的含義是什么?

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 )。

我發現了以下問題,該問題擴展了到目前為止收到的答案: 如何從Typescript的通用類中的Type參數創建新對象?

使用泛型在TypeScript中創建工廠時,有必要通過其構造函數來引用類類型。 因此,不要使用type:T ,而要使用type:{new():T;}

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

更多細節在這里

在您的示例中, 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>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM