Sub topic 11
Transforms and input versus output types
This chapter assumes you can build a form with useForm, register, handleSubmit, and zodResolver, and that you can read TypeScript generics.
Why input and output differ
An HTML input always gives you a string, even for type="number". Your API probably wants a number. A Zod transform converts the value after validation passes, so the schema describes two types:
- The input type is what the form holds while the user types.
- The output type is what the schema returns after parsing, and what
handleSubmitpasses to your callback.
Without a transform the two types are identical, which is why z.infer has been enough so far. Once you add a transform they diverge.
Reading the two types
Zod provides z.input and z.output to name each side. z.infer is an alias for z.output.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const orderSchema = z.object({
quantity: z
.string()
.regex(/^\d+$/, "Digits only")
.transform(Number),
});
type OrderInput = z.input<typeof orderSchema>;
type OrderOutput = z.output<typeof orderSchema>;
export function OrderForm() {
const { register, handleSubmit } = useForm<OrderInput, unknown, OrderOutput>({
resolver: zodResolver(orderSchema),
defaultValues: { quantity: "1" },
});
return (
<form
onSubmit={handleSubmit((values) => {
console.log(typeof values.quantity); // "number"
})}
>
<input {...register("quantity")} />
<button type="submit">Order</button>
</form>
);
}useForm takes three type arguments:
| Position | Name | Used for |
|---|---|---|
| 1 | Field values | `register`, `defaultValues`, `watch`, `errors` |
| 2 | Context | Data passed to the resolver. Here `unknown`. |
| 3 | Transformed values | The argument of the `handleSubmit` callback |
The regex check runs before the transform, so "abc" produces the error "Digits only" and the callback never runs.
Common errors
- Passing only one type argument. With
useForm<OrderOutput>, TypeScript expectsquantityto be a number indefaultValuesandregister. The form then disagrees with what the input actually holds. - Using
z.inferfor the form values. It gives the output type. That is correct for the submit callback and wrong for default values when a transform exists. - Transforming and expecting
resetto hold output.resetandwatchwork with input values. Only the submit callback sees output values. - Putting checks after a transform. After
.transform(Number)the value is a number, so string methods like.regexare no longer available. Validate the string first.
Exercise
A schema has age: z.string().transform(Number). Which type should defaultValues.age have, and which type does the handleSubmit callback receive for age?
Show answer
defaultValues.age uses the input type, so it is a string such as "18". The callback receives the output type, so age is a number. Declare both with useForm<z.input<typeof schema>, unknown, z.output<typeof schema>>.