How to get response type depending on the input params?
Simple example of a normal JS function with generics:
This is what I want to achieve with TRPC. If I send some params I want my respone type be able to change depending on the params. How can I achieve that?
5 Replies
I already checked this page in the docs, but this does not describe my use case (https://trpc.io/docs/infer-types)
Simplest way would be using a discriminated union: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#discriminating-unions
Handbook - Unions and Intersection Types
How to use unions and intersection types in TypeScript
But that's not exactly what you're showing in the TS example
Maybe a router factory if it's for a known set of entities and you don't mind splitting them up among routes: https://dev.to/nicklucas/trpc-patterns-router-factories-and-polymorphism-30b0
DEV Community
tRPC & React Patterns: Router Factories
This post comes in 2 halves: tRPC Router Factories Consuming Router Factories in a React...
True covariance of inputs in TS is a challenge because it can be achieved via method overloads, but that's not type-safe on the inside