Tom Nurkkala Tom Nurkkala - 3 months ago 15
TypeScript Question

Typescript function declaration uses new()

What is the meaning of the type declaration for

dialogComponent
in the following Typescript code snippet?

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


(From https://www.lucidchart.com/techblog/2016/07/19/building-angular-2-components-on-the-fly-a-dialog-box-example).

I found the following question that expands on answers received so far: How to create a new object from type parameter in generic class in typescript?

Answer

In your example dialogComponent is the actual class and not an instance of it, or in other words it's the constructor function of the class.
Here's an example:

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

As you can see, the factory function expects an object which can be called using the new keyword, and such objects are the classes.

This is widely used in the lib.d.ts, for example the 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>;
}
Comments