Is there a way to improve the way I do type definition of the argument here with the zod object?

const exampleQuery = async (
input: { text?: string | null | undefined } | null | undefined
) => {
return {
greeting: `Hello ${input?.text ?? "world"}`,
};
};

export const exampleRouter = router({
hello: publicProcedure
.input(z.object({ text: z.string().nullish() }).nullish())
.query(({ input }) => {
return exampleQuery(input);
}),
});
const exampleQuery = async (
input: { text?: string | null | undefined } | null | undefined
) => {
return {
greeting: `Hello ${input?.text ?? "world"}`,
};
};

export const exampleRouter = router({
hello: publicProcedure
.input(z.object({ text: z.string().nullish() }).nullish())
.query(({ input }) => {
return exampleQuery(input);
}),
});
5 Replies
mrnicericee
mrnicericee2y ago
You can move the input Zod schema outside, then infer the type from it
amanuel
amanuelOP2y ago
I haven't worked with zod that much, can you show a simple example or just link a reference? Anything is helpful, thank you so much
mrnicericee
mrnicericee2y ago
One sec, not on my computer lol @amanuel could do this
import { z } from "zod";
import { publicProcedure } from "../../trpc";

const inputSchema = z.object({
name: z.string(),
});

type Input = z.infer<typeof inputSchema>;

const greetings = (input: Input) => {
return {
greeting: input.name,
};
};

export const example = publicProcedure
.input(inputSchema)
.query(({ input }) => {
return greetings(input);
});
import { z } from "zod";
import { publicProcedure } from "../../trpc";

const inputSchema = z.object({
name: z.string(),
});

type Input = z.infer<typeof inputSchema>;

const greetings = (input: Input) => {
return {
greeting: input.name,
};
};

export const example = publicProcedure
.input(inputSchema)
.query(({ input }) => {
return greetings(input);
});
amanuel
amanuelOP2y ago
Yes, this is perfec Thank you so much for the example
mrnicericee
mrnicericee2y ago
yeah no worries SippyDuck
Want results from more Discord servers?
Add your server