A. Perkamentus
A. Perkamentus16mo ago

How to get response type depending on the input params?

Simple example of a normal JS function with generics:
const example = <T extends unknown>(params: T): T => {
return params
}

// TYPE: const params: readonly ["Hello", "World"]
const params = ['Hello', 'World']

// TYPE: const result: readonly ["Hello", "World"]
const result = example(params)

// TYPE: const str1: string, const str2: string
const [str1, str2] = result
const example = <T extends unknown>(params: T): T => {
return params
}

// TYPE: const params: readonly ["Hello", "World"]
const params = ['Hello', 'World']

// TYPE: const result: readonly ["Hello", "World"]
const result = example(params)

// TYPE: const str1: string, const str2: string
const [str1, str2] = result
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?
// TYPE: const params: readonly ["Hello", "World"]
const params = ['Hello', 'World']

const { data } = trpc.router.model.example(params)

// I want the following type returned based on the params
// TYPE: const result: readonly ["Hello", "World"]
const result = data;

// I want the same result as in the simple example
// TYPE: const str1: string, const str2: string
const [str1, str2] = result
// TYPE: const params: readonly ["Hello", "World"]
const params = ['Hello', 'World']

const { data } = trpc.router.model.example(params)

// I want the following type returned based on the params
// TYPE: const result: readonly ["Hello", "World"]
const result = data;

// I want the same result as in the simple example
// TYPE: const str1: string, const str2: string
const [str1, str2] = result
5 Replies
A. Perkamentus
A. Perkamentus16mo ago
I already checked this page in the docs, but this does not describe my use case (https://trpc.io/docs/infer-types)
Nick
Nick16mo ago
Handbook - Unions and Intersection Types
How to use unions and intersection types in TypeScript
Nick
Nick16mo ago
But that's not exactly what you're showing in the TS example
Nick
Nick16mo ago
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...
Nick
Nick16mo ago
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