[英]Typescript passing an Abstract Class as Generic constraint and construct it
I'm using the apollo RESTDataSource我正在使用阿波罗 RESTDataSource
I see it is an abstract class
我看到它是一个abstract class
I'm creating a function to instantiate this DataSource
(which are normal Class
es), to pass back to the user to allow them to call a specific function on the DataSource
- essentially the responsibility of constructing the DataSource is with my function, but I allow the caller to specify which method to call.我正在创建一个函数来实例化这个DataSource
(它们是普通的Class
es),传递回用户以允许他们调用DataSource
上的特定函数 - 本质上构造 DataSource 的责任在于我的函数,但我允许调用者指定要调用的方法。
const httpCaller = <TRequest, TResponse, DataSource extends typeof RESTDatasource>(
args: TRequest,
dataSourceConstructor: DataSource,
httpExecutor: (ds: DataSource, args: TRequest) => Promise<TResponse>
) {
const dataSourceFactory = (args: TRequest) => {
const ds = new dataSourceConstructor();
ds.initialize({ context: {}, cache })
return httpExecutor(ds, args);
}
// this const gets passed down into other functions and at some point (the right point it gets called)
doingOtherStuff(args, dataSourceFactory);
}
Currently it complains that Cannot create an instance of an abstract class.ts(2511)
which, I get, but I thought, that if DataSource extends
then that doesn't necessarily mean that DataSource
is an abstract... I've tried doing & { new(...args: any[]) => any }
, however, that just shuts up the error on new dataSourceConstructor()
line, but when I pass MyCustomDataSource
, it complains...目前它抱怨Cannot create an instance of an abstract class.ts(2511)
,我明白了,但我想,如果DataSource extends
那么这并不一定意味着DataSource
是一个抽象......我试过这样做& { new(...args: any[]) => any }
,但是,这只是关闭了new dataSourceConstructor()
行上的错误,但是当我通过MyCustomDataSource
,它会抱怨...
I've read a few things, but I can't find the answer.我读了一些东西,但我找不到答案。
does this suffice?这足够了吗?
const httpCaller = <TRequest, TResponse, DataSource extends RESTDatasource>(
args: TRequest,
dataSourceConstructor: { new(...args: any[]): DataSource },
httpExecutor: (ds: DataSource, args: TRequest) => Promise<TResponse>
) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.