I'm currently working on a function that has the capability to call multiple APIs while providing strong typing for each parameter: api
- which represents the name of the API, route
- the specific route within the 'api', and params
- a JSON object containing the required parameters for the chosen API and route.
To better illustrate what I have in mind, I've created an example using the TS Playground here.
The code snippet is as follows:
type APINames = "google" | "yahoo";
type Routes<A extends APINames> = {
google: "endpoint1" | "endpoint2";
yahoo: "endpoint3";
}[A];
type RouteParams<A extends APINames, R extends Routes<A>> = {
google: {
endpoint1: {
name: string;
};
endpoint2: {
otherName: string;
};
};
yahoo: {
endpoint3: {
otherOtherName: string;
};
};
}[A][R];
const execute = <A extends APINames, R extends Routes<A>>(api: A, route: R, params: RouteParams<A, R>) => {
// ... code
}
execute('google', 'endpoint1', {
name: 'George Washington'
});
There seems to be a type error arising from my RouteParams
type. The issue lies in the fact that, although [A]
serves as a valid first index, [R]
does not qualify as a legitimate second index due to the fact that R
now holds the type
'endpoint1' | 'endpoint2' | 'endpoint3'
, and certain subsets of those values do not align with all keys present within the RouteParams
object. Despite this setback, the provided code does offer useful typing assistance when utilizing the execute
function. It's imperative for me to resolve the TypeScript error pertaining to RouteParams
. I suspect that there might be a utility type out there capable of addressing this issue, and I am also open to exploring solutions involving completely different structures.
Ultimately, the main objective is to create a function that accepts three arguments: the first being an API name selected from a union type, the second representing a route derived from a union type associated with the specified API, and the third consisting of a JSON parameters object linked to the combination of the API name and route.