I am exploring the creation of a type-safe API-SDK where each entity supports different API endpoints based on an enum. In this scenario, only two out of three entities allow posting. Although calling the post-function with a known type resolves correctly, looping over all the endpoints supporting post introduces an unexpected return type void
, which poses challenges when passing it to other functions that do not accept void
. The example provided below illustrates this issue. How can I eliminate the void
return type from the post-function or replace it with never
?
enum Entity {
Person,
Organization,
Job,
}
interface Person {}
interface Organization {}
const entityEndpointsSupportingPost= [Entity.Person, Entity.Organization];
type EntityEndpointsSupportingPost = {
[Entity.Person]: Person;
[Entity.Organization]: Organization;
[Entity.Job]: void;
}
async function postEntity<T extends keyof EntityEndpointsSupportingPost>(endpoint: T): Promise<EntityEndpointsSupportingPost[T]> {
const result = await fetch(`api/${endpoint}`);
return await result.json();
}
const person = Entity.Person;
// The type here is recognized as Promise<Person>
const postedPerson = postEntity(person);
for (const entity of entityEndpointsSupportingPost) {
// The type in this loop becomes Promise<void | Person | Organization>
const postedEntity = postEntity(entity);
}