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

Query Procedures and Type Inference

Creating query procedures that automatically infer return types on the client without manual type annotations.

Query Procedures and Type Inference

You'll learn how tRPC's query procedures automatically infer their return types on the client without requiring manual type annotations.

The Automatic Type Flow

When you create a query procedure in tRPC, something magical happens: the client automatically knows the exact return type without you having to write it twice. This is type inference taken to its logical extreme—your backend procedure's return value becomes the frontend type.

Think of it like a postal service that automatically prints the contents label on every package. You put something in the box on the server side, and the label on the client side instantly updates to tell you exactly what's inside—no manual labeling required.

How It Works

With the Zod validators you learned in the previous lesson, you defined what comes into your procedure (the input). Now, whatever your procedure returns flows directly to the client's type system:

Server:

export const appRouter = router({
  getUser: publicProcedure
    .input(z.object({ id: z.string() }))
    .query(async ({ input }) => {
      // TypeScript infers the return type from what you actually return
      return {
        id: input.id,
        name: "Alice",
        age: 30,
        isActive: true
      };
    })
});

Client:

const result = await trpc.getUser.query({ id: "123" });

// result is automatically typed as:
// { id: string; name: string; age: number; isActive: boolean }

console.log(result.name); // ✓ TypeScript knows this exists
console.log(result.email); // ✗ Error: Property 'email' does not exist

No interface declarations, no manual type annotations, no duplication. The return type flows automatically from implementation to consumption.

Why This Matters

This pattern solves the "two sources of truth" problem. Without inference, you'd define the return type on the server, then copy-paste it to the client. Change one, update the other—forever. Query procedure inference means your implementation is your contract.

Key Takeaway: Query procedures in tRPC infer their return types automatically, giving clients compile-time safety without manual type duplication between server and client code.