'Typescript is it possible to infer types based on argument enum?

Let's say that I have a function that has 3 arguments. The first argument is an enum that is defined by me, the second argument is an object that has the shape based on the value passed by the enum. The third argument is just a string.

Look at this function:

  async callApi<Response = any, Input = any>(
    op: ApiOperations,
    input: Input,
    functionName: string
  ): Promise<Response> {
    return this.lambda.invoke<Response>(functionName, {
      op,
      input
    });
  }

You can see that I'm declaring this function as generic and receiving two types and setting the default to any and that works. But in this case whenever I want to call this function I have to manually specify the input and response types. The thing is, I know that for each value from my ApiOperations enum, I have just one input type and one response type.

So my question is, is there any way of typescript can infer the types based on the enum value?

An example of calling this function is:

  async getChatRooms({ numberResults, siteId, startIndex }: GetChatRoomsInput): Promise<ChatRoom[]> {
    return this.api.callApi<ChatRoom[], GetChatRoomsInput>(ApiOperations.GetChatRooms, {
      siteId,
      numberResults,
      startIndex
    }, 'getChatRooms');
  }

This works fine, but the way that I want to do is:

  async getChatRooms({ numberResults, siteId, startIndex }: GetChatRoomsInput): Promise<ChatRoom[]> {
    return this.api.callApi(ApiOperations.GetChatRooms, {
      siteId,
      numberResults,
      startIndex
    }, 'getChatRooms');
  }

And for this case typescript would be able to tell me that the input has the GetChatRoomsInput type and ChatRoom[] as the response type.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source