Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 727
Tom Nurkkala Avatar asked Sep 07 '25 18:09

Tom Nurkkala


1 Answers

When creating factories in TypeScript using generics, it is necessary to refer to class types by their constructor functions. So instead of using type:T, use type: { new(): T;}.

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

More details at here.

like image 85
Ha Hoang Avatar answered Sep 10 '25 07:09

Ha Hoang