Gabriel
Gabriel10mo ago

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
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,
}),
),
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
Jump to solution
3 Replies
Nick
Nick10mo ago
You’re usually best to go with a Router Factory for this type of situation, so you produce two separate routers but with a different Parser provided and the types get inferred nicely
Nick
Nick10mo ago
DEV Community
tRPC & React Patterns: Router Factories
This post comes in 2 halves: tRPC Router Factories Consuming Router Factories in a React...
Solution
Nick
Nick10mo ago
Alternatively you can use a Zod Union type on the input