Search code examples
javascripttypescriptweb

Get type for an object's values where each object is of type <string,function>, and each function have different argument


The object looks like this

export const templates = {
  [EventType.EventType1 + OutputSources.Email]: (params: { documentName: string; link: string }) => {
    return "some html data";
  },
  [EventType.EventType2 + OutputSources.Email]: (params: { documentName: string }) => {
    return "some html data";
  },
  [EventType.EventType1 + OutputSources.Notification]: (params: { documentName: string }) => {
    return "some html data";
  },
} as const;

I want to have a type that contains parameters of each of these function as a union, for example the result for above will look like. type possibleFunctionArgs = {documentName:string,link:string} | {documentName:string}

What I've already tried and failed type lastFailingAttemptToGetTypes = Parameters<typeof templates[keyof typeof templates]> For the above code I'm always getting only {documentName:string,link:string} , always getting the one with highest number of parameters


Solution

  • For that to work you need your keys to be constant strings
    If your EventType.EventType1, etc are constants, you may use template strings to merge their type

    export const templates = {
      [`${EventType.EventType1}${OutputSources.Email}`]: (params: { documentName: string; link: string }) => {
        return "some html data";
      },
      [`${EventType.EventType2}${OutputSources.Email}`]: (params: { documentName: string }) => {
        return "some html data";
      },
      [`${EventType.EventType1}${OutputSources.Notification}`]: (params: { documentName: string }) => {
        return "some html data";
      },
    } as const;
    type A = typeof templates
    //   ^?
    type B = A[keyof A]
    //   ^?
    type C = Parameters<B>[0]
    //   ^?