Course contentsShow
← TypeScript
Lesson 1574 of 1,79636. tRPC and End-to-End Type SafetyFree lesson

Nested Router Type Inference

How tRPC maintains type safety when procedures are organized in nested router structures.

Nested Router Type Inference

You'll learn: How tRPC maintains complete type safety when you organize API procedures into nested router structures, ensuring that deeply nested routes remain fully typed across client and server.

The Nested Router Challenge

As your API grows, you naturally want to organize procedures into logical groups—auth routes, user routes, post routes, admin routes, etc. In traditional REST APIs, this organization is purely runtime, with no compile-time guarantees. tRPC's nested routers maintain full type inference through arbitrary levels of nesting.

How Nested Router Type Inference Works

When you create nested routers in tRPC, each sub-router is just another router object that gets merged into a parent router. The TypeScript compiler tracks the entire tree structure as a single type, preserving the full path to every procedure.

const userRouter = t.router({
  getProfile: t.procedure.query(() => ({ name: "Alice", age: 30 })),
  updateProfile: t.procedure.mutation(() => ({ success: true })),
});

const postRouter = t.router({
  list: t.procedure.query(() => [{ id: 1, title: "Hello" }]),
  create: t.procedure.mutation(() => ({ id: 2 })),
});

// Nest routers under a parent
const appRouter = t.router({
  user: userRouter,
  post: postRouter,
});

// The type system knows the FULL path structure:
// appRouter contains:
//   - user.getProfile (query)
//   - user.updateProfile (mutation)
//   - post.list (query)
//   - post.create (mutation)

On the client side, these nested paths become fully typed method chains:

// TypeScript knows this path exists and what it returns
const profile = await trpc.user.getProfile.query();
// profile is typed as { name: string; age: number }

const posts = await trpc.post.list.query();
// posts is typed as Array<{ id: number; title: string }>

The Type Propagation Magic

The key insight is that AppRouter captures the entire nested structure as a TypeScript type. When you create your client, it recursively transforms this router type into a client type where each level of nesting becomes a property access, and each leaf procedure becomes a callable method.

The type system understands arbitrary nesting depth—routers inside routers inside routers—because TypeScript's structural type system can represent and traverse these recursive structures at compile time.

Key Takeaway: tRPC's nested router type inference means you can organize your API into logical hierarchies without sacrificing type safety—every nested procedure path is fully typed from server definition to client invocation.