如何确保Class的参数类型实现接口

时间:2018-11-05 17:07:38

标签: typescript

我有一个实现接口IField的类

export class FieldImplementation implements IField { };

还有一个存储类型的服务:

import { FieldImplementation } from '../component';
...
service.addField(FieldImplementation);

我需要确保传递给addField的参数实现IField

当前addField看起来像这样:

addField(field: any) {
...
}

1 个答案:

答案 0 :(得分:1)

您正在寻找构造函数签名,也称为a "newable" type。您希望将addField()的参数作为您调用new来获得IFIeld的参数。可以这样表示:

addField(field: new(...args: any[])=>IField) {
  // ...
  new field(/* some kind of arguments */);
}

该签名将接受产生IField的任何构造函数,但可能与构造函数接受的参数不匹配。


如果您期望fieldnew以及特定数量和类型的参数来调用,您也可以表示出来。例如,如果您希望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();

希望有帮助。祝你好运!

相关问题