Sub topic 14
Input types versus output types
This chapter assumes you can read basic TypeScript generics and typeof. It also assumes you know how parse, safeParse, transform, default, and coerce work from earlier chapters. Examples use Zod 3.x and 4.x unless noted.
Why a schema has two types
Until now, a schema described one shape. Once a schema can change data, that stops being true. A schema that coerces, defaults, or transforms accepts one type and produces another.
Zod tracks both:
- The input type is what the schema accepts. It is the type of the argument to
parse, if you want to describe that argument precisely. - The output type is what
parsereturns on success.
For a schema with no transforms, defaults, or coercion, the two types are identical. That is why z.infer seemed enough earlier. z.infer<typeof S> is an alias for z.output<typeof S>. It always gives you the output side.
import { z } from "zod";
const Length = z.string().transform((s) => s.length);
type LengthInput = z.input<typeof Length>; // string
type LengthOutput = z.output<typeof Length>; // number
type LengthInferred = z.infer<typeof Length>; // number, same as outputWhich features change the types
Only some features make the two sides differ. The table lists the common ones.
| Schema | Input type | Output type | Column | Column |
|---|---|---|---|---|
| `z.string()` | `string` | `string` | ||
| `z.string().min(3)` | `string` | `string` | ||
| `z.string().refine(...)` | `string` | `string` | ||
| `z.string().optional()` | `string \ | undefined` | `string \ | undefined` |
| `z.string().default("guest")` | `string \ | undefined` | `string` | |
| `z.string().transform((s) => s.length)` | `string` | `number` | ||
| `z.coerce.number()` | `unknown` in Zod 4, `number` in Zod 3 | `number` |
Three rules follow from the table:
- Checks such as
min,max, andrefinenever change a type. They only reject values. defaultwidens the input, because the key may be missing, and narrows the output, because the value is always present.transformreplaces the output type with whatever your function returns.
The coercion row differs between versions. Zod 3 types the input of z.coerce.number() as number, even though at runtime it accepts anything Number() can convert. Zod 4 reports it honestly as unknown. If you rely on z.input for coerced fields, check which major version you have installed.
Object schemas combine both sides
For an object schema, Zod builds the input and output object types field by field. Take a booking form where every value starts as a string:
import { z } from "zod";
const Booking = z.object({
guests: z.string().transform(Number).pipe(z.number().int().min(1)),
date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.transform((s) => new Date(s)),
notes: z.string().default(""),
});
type BookingInput = z.input<typeof Booking>;
// { guests: string; date: string; notes?: string | undefined }
type BookingOutput = z.output<typeof Booking>;
// { guests: number; date: Date; notes: string }The pipe call feeds the result of the transform into a second schema. This lets you convert a string to a number and then check that it is an integer of at least 1. A plain transform(Number) would accept "abc" and produce NaN, so the second schema matters.
Notice what happened to notes. In the input type it is optional, because default lets the caller omit it. In the output type it is a required string. Code that receives parsed data never has to check for undefined.
Using each type where it belongs
The input type describes data before validation. The output type describes data after validation. Use each for the matching job.
// Form state: matches what the user typed, so use the input type.
function emptyForm(): z.input<typeof Booking> {
return { guests: "1", date: "2026-01-01" };
}
// Business logic: runs only on validated data, so use the output type.
function describeBooking(b: z.output<typeof Booking>): string {
return `${b.guests} guest(s) on ${b.date.toISOString().slice(0, 10)}`;
}
const result = Booking.safeParse(emptyForm());
if (result.success) {
console.log(describeBooking(result.data));
// "1 guest(s) on 2026-01-01"
}If you typed emptyForm with z.infer, TypeScript would demand guests: number and date: Date. A form field holds neither. The compiler would push you toward casts that hide real bugs.
As a rule of thumb:
- Form defaults, test fixtures for raw payloads, and request types on an HTTP client use
z.input. - Functions that receive parsed data, database writes, and domain logic use
z.output(orz.infer).
Writing generic helpers
When you write a helper that accepts any schema, return the output type. Constrain the parameter with z.ZodType:
import { z } from "zod";
function parseOrThrow<S extends z.ZodType>(schema: S, data: unknown): z.output<S> {
return schema.parse(data);
}
const port = parseOrThrow(z.coerce.number().int(), "8080");
// port: numberThe helper takes data: unknown because the whole point of a schema is to accept data you have not yet verified. If you want callers to pass data that is already shaped like the input type, use data: z.input<S> instead. That version catches typos at compile time, but it cannot be used for truly untrusted data such as JSON.parse results.
A gotcha: output is not always valid input
Because the two types differ, you cannot assume that a parsed value will pass through the same schema again. This property is called idempotence. Schemas with transforms lack it.
const parsed = Booking.parse({ guests: "2", date: "2026-03-01" });
// parsed.date is a Date object
const again = Booking.safeParse(parsed);
console.log(again.success); // falseThe second parse fails because date is now a Date, and the schema expects a string for it. Bugs of this kind usually show up in three places:
- Serialization.
JSON.stringify(parsed)turns theDateback into a string, butguestsstays a number. The result matches neither the input type nor the output type exactly. If you send parsed data over the wire, validate it with a separate schema on the receiving side, or define the wire format explicitly. - Layered validation. If a controller parses a body and passes the result to a service that parses it again with the same schema, the second parse fails. Parse once at the boundary, then pass output types inward.
- Caching. Storing the output in a cache and reading it back as input has the same problem.
Defaults and optional fields in detail
optional and default look similar but affect the sides differently.
const Settings = z.object({
theme: z.string().optional(),
retries: z.number().default(3),
});
type SettingsIn = z.input<typeof Settings>;
// { theme?: string | undefined; retries?: number | undefined }
type SettingsOut = z.output<typeof Settings>;
// { theme?: string | undefined; retries: number }With optional, an absent value stays absent, so the output is still optional. With default, an absent value is filled in, so the output is required. If you want to make downstream code simpler, prefer default over optional wherever a sensible fallback exists.
A default is applied to the input side of the schema in Zod 3. In Zod 4, default short-circuits and returns the default value as-is, so it must already be a valid output value. Put default before a transform, as in the DEBUG example from the environment chapter, and both versions behave the same way.
Inspecting types when something looks wrong
When a type error mentions a mismatch you do not understand, ask which side you are on. A quick check is to alias both types and hover over them in your editor:
type In = z.input<typeof Booking>;
type Out = z.output<typeof Booking>;Typical symptoms and fixes:
| Symptom | Likely cause | Fix |
|---|---|---|
| `string` is not assignable to `number` in a form helper | Used `z.infer` where input was needed | Switch to `z.input` |
| Property is possibly `undefined` after parsing | Field uses `optional` where `default` would fit | Use `default`, or handle `undefined` |
| Second `parse` of parsed data fails | Schema contains a type-changing `transform` | Parse once, pass output inward |
| Coerced field typed `unknown` in `z.input` | Zod 4 reports coercion input as `unknown` | Type the raw value yourself, for example as `string` |
Exercise
What are z.input and z.output of z.string().default("guest"), and what do they become if you append .transform((s) => s.toUpperCase())?
Show answer
Without the transform, the input is string | undefined and the output is string. After appending the transform, the input stays string | undefined and the output stays string, because toUpperCase returns a string. The transform changes the runtime value but not either type.
Exercise
A handler calls Booking.parse(req.body), then passes the result to saveBooking, which calls Booking.parse again on its argument and throws. Why, and how do you fix it?
Show answer
The first parse turns date from a string into a Date. The second parse expects a string, so it fails. Fix it by parsing only once at the boundary and typing saveBooking's parameter as z.output<typeof Booking>, so no second parse is needed.