Course contentsShow
← TypeScript
Lesson 1550 of 1,79635. TypeScript with Framework Cross-ReferencesFree lesson

Generic Procedures and Reusable Logic

Building reusable procedure factories with generics to reduce boilerplate while maintaining full type inference.

Generic Procedures and Reusable Logic

What you'll learn: How to create reusable tRPC procedure factories with generics that eliminate boilerplate while preserving complete type inference across your API.

The Boilerplate Problem

When building tRPC APIs, you often write similar procedures repeatedly—authentication checks, input transformations, common error handling, or consistent response wrapping. Copy-pasting this logic creates maintenance nightmares, but extracting it without generics loses type information.

Procedure Factories with Generics

The solution is generic procedure factories: functions that accept type parameters and return fully-typed procedures. These factories encapsulate shared logic while maintaining end-to-end type inference:

import { z } from 'zod';
import { TRPCError } from '@trpc/server';

// Generic factory for authenticated procedures
function createAuthProcedure<TInput extends z.ZodType>(
  inputSchema: TInput
) {
  return publicProcedure
    .input(inputSchema)
    .use(async ({ ctx, next }) => {
      if (!ctx.user) {
        throw new TRPCError({ code: 'UNAUTHORIZED' });
      }
      return next({
        ctx: {
          user: ctx.user // Now guaranteed non-null
        }
      });
    });
}

// Use it with full type inference
const updateProfile = createAuthProcedure(
  z.object({
    name: z.string(),
    email: z.string().email()
  })
).mutation(async ({ input, ctx }) => {
  // input: { name: string, email: string }
  // ctx.user: guaranteed present
  return await db.updateUser(ctx.user.id, input);
});

Multiple Type Parameters for Flexibility

Factories can accept multiple generics for input, output, and context transformations:

function createPaginatedQuery<
  TInput extends z.ZodType,
  TOutput
>(
  inputSchema: TInput,
  fetchData: (input: z.infer<TInput>) => Promise<TOutput[]>
) {
  return publicProcedure
    .input(
      inputSchema.extend({
        page: z.number().default(1),
        limit: z.number().max(100).default(20)
      })
    )
    .query(async ({ input }) => {
      const items = await fetchData(input);
      const offset = (input.page - 1) * input.limit;
      
      return {
        items: items.slice(offset, offset + input.limit),
        page: input.page,
        hasMore: items.length > offset + input.limit
      };
    });
}

// Type inference flows through
const listPosts = createPaginatedQuery(
  z.object({ category: z.string() }),
  async ({ category }) => db.posts.where({ category })
);

Generic Error Wrapping Patterns

Factories shine when standardizing error handling across procedures:

function createSafeQuery<TInput extends z.ZodType, TOutput>(
  inputSchema: TInput,
  handler: (input: z.infer<TInput>, ctx: Context) => Promise<TOutput>
) {
  return publicProcedure
    .input(inputSchema)
    .query(async ({ input, ctx }) => {
      try {
        const data = await handler(input, ctx);
        return { success: true as const, data };
      } catch (error) {
        return { 
          success: false as const, 
          error: error instanceof Error ? error.message : 'Unknown error'
        };
      }
    });
}

// Discriminated union return type inferred automatically
const getUser = createSafeQuery(
  z.object({ id: z.string() }),
  async ({ id }) => db.user.findUnique({ where: { id } })
);

// Client usage
const result = await client.getUser.query({ id: '123' });
if (result.success) {
  // TypeScript knows result.data exists
  console.log(result.data);
} else {
  // TypeScript knows result.error exists
  console.error(result.error);
}

Think of It This Way

Generic procedure factories are like cookie cutters for type-safe endpoints. Instead of hand-crafting each procedure, you create reusable shapes that stamp out new procedures while maintaining perfect type inference—no copy-paste, no type loss.

Key Takeaway: Generic procedure factories let you extract common tRPC patterns into reusable functions without sacrificing type safety, dramatically reducing boilerplate while keeping full IDE support and compile-time guarantees.