Input schemas defined with Zod does not use the inferred input type
See original GitHub issueSummary
trpc.router()
.query('greeting', {
input: z.object({
hi: z.string().transform(s => s.length),
}),
resolve({ input }) {
input.hi // => `number`, as expected
},
});
// Somewhere else
client.query('greeting', { hi: 'my greeting' }); // => ERROR: expected `number`
When defining an input schema using zod, I would expect the call site to accept the z.input
version of the schema.
Details
When you define a schema with zod, like this simple one:
const GreetingSchema = z.object({
hi: z.string(),
});
You can infer its type with z.infer
like this:
type Greeting = z.infer<typeof GreetingSchema>;
// Equals
type Greeting = {
hi: string;
}
However, in zod you can also add transformers that change the type of a field, which means the input and output types of the schema are different.
Here’s an example of that:
const GreetingSchema = z.object({
hi: z.string().transform(s => s.length),
});
z.infer
infers the output type of this:
type InferredGreeting = z.infer<typeof GreetingSchema>;
// Equals
type InferredGreeting {
hi: number;
}
To get at the input type, zod also has a z.input
helper (and z.output
, which z.infer
is an alias of), meaning you can get at the version we want:
type InputGreeting = z.input<typeof GreetingSchema>;
type OutputGreeting = z.output<typeof GreetingSchema>;
// Equals
type InputGreeting {
hi: string;
}
type OutputGreeting {
hi: number;
}
This is also mentioned in the README of Zod.
This concept applied to tRPC:
trpc.router()
.query('greeting', {
input: z.object({
hi: z.string().transform(s => s.length),
}),
resolve({ input }) {
input.hi // => `number`, as expected
},
});
// Somewhere else
client.query('greeting', { hi: 'my greeting' }); // => ERROR: expected `number`
In other words, for tRPC I would expect the type required to call a function to be the z.input
type, and the type available in the resolve
function to be the z.output
type.
Issue Analytics
- State:
- Created 2 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
@all-contributors add @kimroen for ideas
Got a working branch in #1189 - just waiting for feedback