I am working with a generic interface that has specific constraints applied to its parameters. Here is an example of how it is used:
interface Fetcher<Params,Resp> {
fetch(params: Params): Resp;
};
In my code, I have a function that uses this interface with additional constraints on the generic parameters:
function paginateWithSearch<Params extends (PaginationParams & SearchParams),
Resp extends SomeItemsResp>(fetcher: Fetcher<Params, Resp>){
//do something
}
The constraints are defined using simple objects like so:
type SearchParams = {
query: string
};
However, I am facing difficulties in making these constraints work properly in practice. For instance, even when the constraints are not met, the code still runs without errors:
//sample implementation with SearchParams only
const searchFetcher: Fetcher<SearchParams, SomeItemsResp> = {
fetch: function(): SomeItemsResp {
throw new Error("Function not implemented.");
}
}
//Should throw error but works ok - not extending PaginationParams
paginateWithSearch(searchFetcher);
To solve this issue, I have resorted to inferring generic parameters with conditional types and manually passing them to the function:
//now throws error if inferred manually
paginateWithSearch<FetcherParamsInfer<typeof searchFetcher>, FetcherRespInfer<typeof searchFetcher>>(
searchFetcher
);
It seems like there might be a simpler solution that I am missing. Any input would be appreciated.