My goal is to implement a factory method for all my Axios API classes that are generated by the OpenAPI generator.
The Open-API tool creates a BaseAPI class with a constructor, and then generates several API classes that extend this BaseAPI based on my Backend Controllers.
I attempted to create the following function:
import { BaseAPI } from "@/api/base";
abstract class AbstractControllerHandler {
protected createApi<T extends typeof BaseAPI>(clazz: T) {
return new clazz(
undefined,
"",
AxiosInstanceHolder.getInstance().getAxiosInstance(),
);
}
This function is then utilized by another class:
import { CrudCapitalsourceControllerApi } from "@/api";
class CapitalsourceControllerHandler extends AbstractControllerHandler {
private api: CrudCapitalsourceControllerApi;
public constructor() {
super();
this.api = super.createApi(CrudCapitalsourceControllerApi);
}
}
The CrudCapitalsourceControllerApi
is defined as a subclass of BaseAPI
and is automatically generated by OpenAPI.
When attempting to use the createApi
function, I encountered a ts(2739) error which indicates that the returned type is BaseAPI
, but it cannot be assigned to a variable of type CrudCapitalsourceControllerApi
.
To resolve this issue, I believe I need to specify a return type for the createApi
method. However, simply using T
as the return type resulted in a ts(2322) error because I am returning an instance, not a type. Any suggestions on how I can address this problem? Perhaps something along the lines of "instanceof T" for the return type declaration?