Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
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?
–
–
–
–
–
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.
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>;
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.