Sub topic 11
Transforms and input versus output types
This chapter assumes you can build a form with useForm, register, and handleSubmit. It also assumes you can connect a Zod schema with zodResolver and read z.infer. Here you will see why a schema can have two types, and how React Hook Form uses each one.
Why a schema has two types
HTML inputs always give you strings. Your API usually wants numbers, dates, or trimmed text. A Zod transform converts a value after it passes validation. Once a schema contains a transform, the data going in and the data coming out are different shapes.
Zod exposes both shapes:
z.input<typeof schema>is what the schema accepts. This is the shape of the form's field values.z.output<typeof schema>is what the schema produces after transforms and defaults. This is the shape you send to the server.z.infer<typeof schema>is the same asz.output. It is a good fit when the schema has no transforms, because the two types are then identical.
If you use z.infer for a schema with transforms, your form's field type claims quantity is a number. At runtime the input holds a string. TypeScript will not warn you about that mismatch.
The pipeline
The resolver runs the whole schema. If a check fails, the errors go to formState.errors and the transform output is discarded. Your submit callback runs only when parsing succeeds, and it receives the transformed result.
A transform with three type arguments
useForm accepts three generic arguments: the field values, a context type, and the output passed to handleSubmit. Pass z.input first and z.output third.
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>
);
}Here OrderInput is { quantity: string } and OrderOutput is { quantity: number }. The second argument, unknown, is the context type. You only change it if you pass a context option to useForm.
The regex check comes before transform(Number) on purpose. Without it, "abc" would become NaN and pass as a number. When the regex fails, the transform does not run, and the user sees "Digits only".
Which type applies where
| API | Type it uses |
|---|---|
| `defaultValues`, `reset(values)` | Input |
| `register("quantity")` path names | Input |
| `watch`, `getValues`, `useWatch` | Input |
| `setValue` | Input |
| `handleSubmit(callback)` argument | Output |
| `formState.errors` keys | Input |
The rule is simple. Everything that reads or writes the live form uses the input type, because the DOM holds strings. Only the callback passed to handleSubmit sees the parsed output.
Common transforms for forms
A few transforms come up in almost every form:
- Trim:
z.string().trim()removes whitespace before length checks run, so" "failsmin(1). - Lowercase:
z.string().email().toLowerCase()normalizes an email before you send it. - Empty string to undefined: an empty optional input is
"", notundefined. Convert it, or an "optional" field will fail its own number rule. - Number from string: use
transform(Number)after a regex, as above, or a pipe to a number schema.
This example combines several of them. It uses pipe to hand the transformed value to a second schema, so the number is validated as a number.
import { z } from "zod";
const profileSchema = z.object({
displayName: z.string().trim().min(1, "Name is required"),
age: z
.string()
.transform((value) => (value.trim() === "" ? undefined : Number(value)))
.pipe(
z
.number({ invalid_type_error: "Enter a number" })
.int("Whole numbers only")
.min(18, "Must be 18 or older")
.optional(),
),
});
type ProfileInput = z.input<typeof profileSchema>;
// { displayName: string; age: string }
type ProfileOutput = z.output<typeof profileSchema>;
// { displayName: string; age?: number | undefined }
const result = profileSchema.safeParse({ displayName: " Ada ", age: "" });
if (result.success) {
console.log(result.data); // { displayName: "Ada", age: undefined }
}The invalid_type_error option is Zod 3 syntax. In Zod 4, pass the message with the error option instead. Check which major version your project uses before copying error-message options.
Defaults change the types too
.default() also makes the two types differ. A field with .default("USD") is optional in the input and required in the output.
import { z } from "zod";
const priceSchema = z.object({
currency: z.string().default("USD"),
});
type PriceInput = z.input<typeof priceSchema>; // { currency?: string | undefined }
type PriceOutput = z.output<typeof priceSchema>; // { currency: string }Prefer defaultValues in useForm for what the user sees in the input. Use a schema .default() only for values the user may leave out of the data entirely. Both together are fine, but the form's defaultValues is what fills the inputs.
Gotchas
- Coercion and the input type.
z.coerce.number()accepts anything and converts it withNumber(). In Zod 3 its input type isnumber, so TypeScript will not complain when the field really holds a string. In Zod 4 the input type isunknown, which can break type checks ondefaultValuesandregister. Inspectz.inputfor your version before relying on coercion. valueAsNumberis not a transform.register("age", { valueAsNumber: true })makes React Hook Form convert the DOM value before validation, so the input type becomesnumber. An empty input yieldsNaN. Pick one approach per field: either the schema transforms strings, orvalueAsNumbersupplies numbers. Mixing them produces confusing type errors.- Transforms hide side effects. A transform runs on every validation pass, including
onChangemode. Keep transforms pure and cheap. Do not call APIs from them. - Resolver type mismatches. If TypeScript reports that the resolver is not assignable to
Resolver<OrderInput, ...>, the cause is usually a missing third generic onuseForm. Without it, the resolver's output type does not match the form's single type. resettakes input values. After a successful submit, callresetwith strings, not with the parsed output.
Choosing an approach
| Situation | Approach |
|---|---|
| Schema has no transforms | `z.infer` and `useForm<Values>` |
| Strings turn into numbers or dates | `useForm<Input, unknown, Output>` |
| Empty optional text input | Transform `""` to `undefined`, then pipe to the real schema |
| Number input, simple case | `valueAsNumber` and a number schema, with no transform |
Exercise
A schema defines age: z.string().transform(Number). You write type Values = z.infer<typeof schema> and call useForm<Values>({ resolver: zodResolver(schema) }). What is wrong, and how do you fix it?
Show answer
z.infer is the output type, so Values["age"] is number, but the form fields hold strings and the resolver's input type is string. The types disagree, so TypeScript reports a resolver mismatch or, worse, hides a bug. Define type Input = z.input<typeof schema> and type Output = z.output<typeof schema>, then call useForm<Input, unknown, Output>({ resolver: zodResolver(schema) }). Then defaultValues takes { age: "" }, and the handleSubmit callback receives age as a number.
Exercise
A form has an optional "age" text input. Users who leave it blank see "Expected number, received nan". Which change in the schema fixes it, and what is the output type of age afterward?
Show answer
Transform the empty string to undefined before the number check, for example z.string().transform((v) => (v.trim() === "" ? undefined : Number(v))).pipe(z.number().int().min(18).optional()). The output type of age is number | undefined, and the input type stays string.