I am building a application and part of the code allows developer to specify which component they want to render a certain part. I want users to know they need to implement an interface but I am not sure how to write typing correctly.
export interface ICustomComponent {
templateObject: any;
}
export class MyComponent implements ICustomComponent {
}
export class MyLib {
constructor(
private yourComponent: ICustomComponent
) {}
}
new MyLib(MyComponent); <== Fails
I am writing code with Angular, and I cannot run new operator but let Angular to resolve and construct that component.
Here an example that illustrates my problem.
How to deal with this problem?
Since MyLib expects a class constructor, not class instance, you need to define an interface for a class constructor and specify that it returns the instance with the ICustomComponent interface:
interface ICustomComponent {
templateObject: any;
}
interface ICustomComponentConstructor {
new (...deps: any[]): ICustomComponent;
}
And then you can use it like this:
export class MyComponent implements ICustomComponent {
templateObject: any;
}
export class MyLib {
constructor(private yourComponent: ICustomComponentConstructor) {
}
}
new MyLib(MyComponent);
You can read about interface for class constructors and instances here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With