[英]How to define an interface for a class instance using class constructor
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. 我正在使用Angular编写代码,我无法运行new运算符,但让Angular解析并构造该组件。
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: 由于MyLib
需要一个类构造函数而不是类实例,因此需要为类构造函数定义一个接口,并指定它返回带有ICustomComponent
接口的实例:
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 . 您可以在此处阅读有关类构造函数和实例的接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.