There are other ways to structure this that might be better, but what you are asking for is pretty straight-forward. I am separating the arguments for the domain
and the path
so that you can get autocomplete support on the domain name. I am saying that the domain must be one of the keys in your custom map, so you'll get an error if you try to access something with an unknown return type.
This typedApi
function takes the domain and the path and then calls the root api
function with the correct return type based on the domain.
const typedApi = <Domain extends keyof CustomMap>(domain: Domain, path: string): Promise<CustomMap[Domain]> => {
return api<CustomMap[Domain]>(`https://${domain}${path}`);
}
// Promise<{ id: string; name: string; }>
const gData = typedApi('google.com', '/some-path');
// Promise<{ count?: number }>
const aData = typedApi('amazon.com', '/some-path');
Playground Link
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…