[英]Can I define a generic typescript Interface for the methods of a Class?
I'm cleaning up the types of my Angular 4 Application and I would like to define an interface to the Database
classes in charge of the API calls. 我正在清理Angular 4应用程序的类型,并且想定义一个负责API调用的
Database
类的接口。
Those classes will have methods receiving Criteria
objects, and returning Observables of ResultItems[]
that are widely different. 这些类将具有接收
Criteria
对象并返回ResultItems[]
很大的ResultItems[]
Observables的ResultItems[]
。 So I've tried to define this Interface: 所以我尝试定义此接口:
import { Observable } from 'rxjs/Observable';
export interface Database<C> {
[methodName: string]: (args: C) => Observable<any>;
}
to cover the methods receiving a Criteria
and returning any
thing. 涵盖接收
Criteria
并返回any
东西的方法。
Then I try to have this kind of implementation: 然后,我尝试进行这种实现:
@Injectable()
export class ItemsDatabase<ItemsCriteria> implements Database<ItemsCriteria> {
constructor(private api: ApiService) {}
fetch(args: ItemsCriteria): Observable<APIResponse[]> {
return this.api.fetchItems(args);
}
summary(args: ItemsCriteria): Observable<SummaryResponse[]> {
return this.api.itemsSummary(args);
}
}
but Typescript denies it throwing: 但Typescript拒绝抛出:
Class 'ItemsDatabase<ItemsCriteria>' incorrectly implements interface 'Database<ItemsCriteria>'.
Index signature is missing in type 'ItemsDatabase<ItemsCriteria>'
Any advice? 有什么建议吗? or this is just not possible?
还是这是不可能的? Thanks in advance!
提前致谢!
You have to add the index signature to the class 您必须将索引签名添加到类中
@Injectable()
export class ItemsDatabase<ItemsCriteria> implements Database<ItemsCriteria> {
constructor(private api: ApiService) {}
[methodName: string]: (args: ItemsCriteria) => Observable<any>;
fetch(args: ItemsCriteria): Observable<APIResponse[]> {
return this.api.fetchItems(args);
}
summary(args: ItemsCriteria): Observable<SummaryResponse[]> {
return this.api.itemsSummary(args);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.