I'm interested in creating a custom type that functions can use to indicate to callers that an input parameter of a specific type corresponds to a certain output type.
For instance, consider the following scenario:
type ResponseMap =
{ requestPath: "/user/", response: UserData } |
{ requestPath: "/posts/", response: PostData };
async function getRequest<Value extends ResponseMap>(
path: Value["requestPath"]
): Promise<Value["response"] | undefined> {
const response = await fetch(path);
return response.json();
}
// This currently throws an error because `PostData` cannot be
// assigned to `UserData | undefined`
const response: UserData | undefined = await getRequest("/user/");
While I understand that function overloads could achieve something similar, I'm seeking a way to reuse ResponseMap
in other functions. Is this achievable in TypeScript?