Subscription Type Inference
You'll learn: How tRPC automatically infers types for real-time streaming data sent from server to client over WebSocket subscriptions, maintaining end-to-end type safety even for live updates.
What Makes Subscriptions Different
Unlike queries (read once) and mutations (write once), subscriptions are ongoing streams of data. Think of them like a news ticker: the server continuously pushes updates, and the client receives them in real-time.
The challenge? Each message flowing through that WebSocket connection needs to be type-safe. You want autocomplete on the client for events the server emits, and compile-time errors if the server changes what it sends.
How tRPC Maintains Type Safety for Streams
When you define a subscription procedure on your tRPC router, the framework analyzes:
- The input type (what parameters the client sends to start the subscription)
- The output type (what shape each emitted event has)
- The emission pattern (whether you're sending complete objects, incremental updates, or discriminated union events)
tRPC's type inference propagates this information to the client. When your client calls .subscribe(), TypeScript knows exactly what data structure each message will contain—before any data arrives.
The Type Flow
Imagine a server subscription that emits status updates:
- Server defines: "I emit objects with
{ status: string; timestamp: number }" - tRPC infers the subscription output type automatically
- Client receives: strongly-typed callback parameters matching that exact shape
- Any mismatch (server changes the shape) triggers a compile error on the client
This works because the router type (AppRouter) includes subscription signatures, and the typed client extracts those signatures to generate properly-typed .subscribe() methods.
Why This Matters for Streaming Data
Without type inference, you'd cast WebSocket messages with assertions, losing safety. With tRPC subscriptions, every real-time message is as type-safe as a synchronous function call—the compiler validates your entire event stream.
Key Takeaway: tRPC's subscription type inference ensures that streaming data over WebSockets maintains the same end-to-end type safety as queries and mutations, giving you compile-time guarantees about every message shape in your real-time communication.