GabrielG
tRPC2y ago
5 replies
Gabriel

How do I pass a Generic to a trpc query procedure?

I want to to something like this:
type AppIdsWithConfig = typeof kodixCareAppId | typeof calendarAppId;

const fakeProcedure = <T extends AppIdsWithConfig>(kodixAppId: T) => {
  const appIdToValue = {
    [kodixCareAppId]: "my value 1",
    [calendarAppId]: 1235,
  } as const;

  return appIdToValue[kodixAppId];
};

const value = fakeProcedure(kodixCareAppId);
//      ^? --> const value: "my value 1"

const value2 = fakeProcedure(calendarAppId);
//      ^? --> const value2: 1235


This is how you pass a generic to a function, as we know. I wanted to do it in a procedure. Right now I have a procedure:
type AppIdsWithConfig = typeof kodixCareAppId | typeof calendarAppId; 

//How do I pass a Generic to this? I want to infer the result type based on the appId I pass in as an input
getConfig: protectedProcedure 
    .input(
      z.object({
        appId: z.custom<AppIdsWithConfig>(),
      }),
    )
    .query(
      async ({ ctx, input }) =>
        await getAppConfig({
          appId: input.appId,
          prisma: ctx.prisma,
          session: ctx.session,
        }),
    ),
Solution
Alternatively you can use a Zod Union type on the input
Was this page helpful?