Eternal Mori
Eternal Mori2y ago

How to infer types from input?

When I call my procedure from the client I send an array of strings as an input. How can I infer the strings so they are returned in the response (see client code comment) On server:
example: publicProcedure
.input(z.object({ names: z.array(z.string()) }))
.query(({ input }) => {
return input.names.reduce((acc, name) => {
return {
...acc,
[name]: Math.random(),
};
}, {});
}),
example: publicProcedure
.input(z.object({ names: z.array(z.string()) }))
.query(({ input }) => {
return input.names.reduce((acc, name) => {
return {
...acc,
[name]: Math.random(),
};
}, {});
}),
On client:
const { data } = trpc.router.example.useQuery({
names: ["Hello", "World"]
})

// infer types from query input / autocomplete
const { Hello, World } = data
const { data } = trpc.router.example.useQuery({
names: ["Hello", "World"]
})

// infer types from query input / autocomplete
const { Hello, World } = data
2 Replies
Hussam
Hussam2y ago
Inferring Types | tRPC
It is often useful to wrap functionality of your @trpc/client or @trpc/react-query api within other functions. For this purpose, it's necessary to be able to infer input types and output types generated by your @trpc/server router.
Eternal Mori
Eternal MoriOP2y ago
I think this is only for getting the response- or the input types. What I want for example:
const {.data } = trpc.example.useQuery(['one', 'two'])

// type of data variable
// readonly ["one", "two"] <- infered from input
const {.data } = trpc.example.useQuery(['one', 'two'])

// type of data variable
// readonly ["one", "two"] <- infered from input

Did you find this page helpful?