简体   繁体   English

如何使用类构造函数为类实例定义接口

[英]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.

相关问题 如何在Typescript中将组件类定义为接口字段? - How to define a component class as an interface field in Typescript? 如何使用类作为变量创建类实例? - How to create class instance using class as variable? 如何覆盖类构造函数? - How to override class constructor? 在某些组件类的构造函数中,“ this”保存类本身而不是实例 - In the constructor of some component class, the 'this' holds the class itself instead of an instance 打字稿:在另一个Class构造函数中创建Class实例的数组 - Typescript: Creating Array of Class instance inside another Class constructor 给定一个接口并实现 class,我如何在构造函数中批量分配属性? - Given an interface and implementing class, how can I mass-assign properties in constructor? Angular2将json observable返回类型定义为接口或类模型 - Angular2 define json observable return type to interface or class model 从实现类的构造函数中获取接口方法的实现 - Get implementation of interface method from constructor of implementing class 如何在Angular 7中使用Typescript使用空构造函数获取类的属性 - How to get properties of a class with empty constructor using Typescript in the Angular 7 如何在使用茉莉花的单元测试Angular类中向类构造函数注入http? - How to inject http to class constructor in unit testing angular class using jasmine?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM