Type Inference Limitations and Workarounds
What you'll learn: Where tRPC's automatic type inference breaks down and how to maintain type safety when you need to step in manually.
When Type Inference Hits Its Limits
tRPC's type inference is incredibly powerful, but it's not magic. In complex scenarios—deeply nested routers, dynamic context transformations, or circular type dependencies—TypeScript's inference engine can struggle or fail entirely. When this happens, you'll see errors like "Type instantiation is excessively deep" or types that resolve to any.
Think of type inference like a detective following clues. Most of the time, it can trace the entire chain from your router to your client. But when the chain becomes too long, has too many branches, or loops back on itself, the detective gets lost. That's when you need to provide explicit hints.
Common Inference Failure Scenarios
Deeply nested routers with many layers can exceed TypeScript's recursion limits. Context mutations in middleware where the shape changes dramatically may confuse inference. Generic procedures that depend on runtime values sometimes can't be fully inferred statically. Circular references between procedures or router types can create impossible inference puzzles.
Manual Type Annotation Strategies
When inference fails, you can provide explicit type annotations:
- Annotate procedure input/output types directly with
.input()and.output()type assertions - Extract and export specific procedure types using
inferProcedureInputandinferProcedureOutpututilities - Create intermediate type aliases for complex nested structures
- Use type parameters on generic procedures to guide inference
- Simplify router nesting to reduce inference depth
The key is finding the right balance: let tRPC infer where it can, but step in with explicit types at bottlenecks where inference struggles.
Maintaining Type Safety with Manual Types
When you add manual types, don't abandon validation. Keep your Zod schemas as the runtime contract, and use them to generate your manual types with z.infer. This ensures your explicit types match reality. Test the boundaries where manual types meet inferred types to catch mismatches early.
Key Takeaway: tRPC's type inference works brilliantly in most cases, but complex scenarios require manual type annotations at strategic points—always backed by runtime validation to keep types honest.