Callum Linington
Callum Linington

Reputation: 14417

Typescript passing an Abstract Class as Generic constraint and construct it

I'm using the apollo RESTDataSource

I see it is an abstract class

I'm creating a function to instantiate this DataSource (which are normal Classes), 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.


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...

I've read a few things, but I can't find the answer.

Upvotes: 3

Views: 90

Answers (1)

D Pro
D Pro

Reputation: 1786

does this suffice?

const httpCaller = <TRequest, TResponse, DataSource extends RESTDatasource>(
  args: TRequest,
  dataSourceConstructor: { new(...args: any[]): DataSource },
  httpExecutor: (ds: DataSource, args: TRequest) => Promise<TResponse>
) {

Upvotes: 1

Related Questions