I have the following generic interface (full playground):
interface Fetcher<Params,Resp> {
fetch(params: Params): Resp;
};
It's used as a function parameter with extra constraints applied to its generic parameters:
function paginateWithSearch<Params extends (PaginationParams & SearchParams),
Resp extends SomeItemsResp>(fetcher: Fetcher<Params, Resp>){
//do something
}
All constraints are represented with simple objects such as:
type SearchParams = {
query: string
};
The tricky part is I can't make this constraints actually work in practice:
//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);
The only way that I've come up with is to infer generic parameters with conditional types and pass them to the function manually:
//now throws error if inferred manually
paginateWithSearch<FetcherParamsInfer<typeof searchFetcher>, FetcherRespInfer<typeof searchFetcher>>(
searchFetcher
);
I should be missing something as it seems like a straightforward problem.