[英]How to ensure that argument type of Class implements an interface
我有一个实现接口IField
的类
export class FieldImplementation implements IField { };
还有一个存储类型的服务:
import { FieldImplementation } from '../component';
...
service.addField(FieldImplementation);
我需要确保传递给addField
的参数实现IField
。
当前, addField
如下所示:
addField(field: any) {
...
}
您正在寻找构造函数签名,也称为“ newable”类型 。 您希望参数addField()
是您为了获得IFIeld
调用的new
东西。 可以这样表示:
addField(field: new(...args: any[])=>IField) {
// ...
new field(/* some kind of arguments */);
}
该签名将接受产生IField
任何构造函数,但可能与构造函数接受的参数不匹配。
如果希望使用new
的参数,特定数量和类型的参数来调用field
,则也可以表示该field
。 例如,如果要让field
成为无参数构造函数:
addField(field: new()=>IField) {
// ...
new field(); // no arguments
}
然后,如果FieldImplementation
是带有无参数构造函数的类,它将成功:
service.addField(FieldImplementation); // okay
而需要构造函数参数的类将失败,这是很好的:
class NeedAString implements IField {
constructor(private myString: string) { }
};
service.addField(NeedAString); // error, NeedAString is not a no-arg constructor
// error is desirable because you don't want addField() implementation
// to call new NeedAString();
希望能有所帮助。 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.