Transforming and Refining Inferred Types
What you'll learn: How schema transforms and refinements affect the inferred output type versus input type in validation libraries.
The Input/Output Type Split
When you create a validation schema with transforms or refinements, something interesting happens: the input type (what data looks like before validation) can differ from the output type (what you get after successful validation).
Think of it like a factory assembly line. Raw materials (input) go in one end, and a finished product (output) comes out the other. The materials and product might look completely different, even though they're connected.
Transforms Change Output Types
When you apply transformations in a schema (like parsing a string into a number, or trimming whitespace), the inferred output type reflects that transformation:
import { z } from 'zod';
const userSchema = z.object({
age: z.string().transform(val => parseInt(val, 10)),
email: z.string().trim().toLowerCase()
});
type UserInput = z.input<typeof userSchema>;
// { age: string; email: string }
type UserOutput = z.output<typeof userSchema>;
// { age: number; email: string }
The input accepts a string for age, but the output is a number because of the transform.
Refinements Don't Change Types
Refinements (custom validation rules) narrow the runtime validity but typically don't change the TypeScript type:
const positiveNumberSchema = z.number().refine(n => n > 0);
type Output = z.infer<typeof positiveNumberSchema>;
// number (not "positive number")
The type is still number, even though only positive numbers pass validation at runtime.
Accessing Both Types
Most schema libraries provide separate utilities to extract input vs output types, letting you type different stages of your data pipeline appropriately.
Key Takeaway: Schema transforms create a gap between input and output types—use z.input for what goes into validation and z.output (or z.infer) for what comes out, while refinements add runtime constraints without changing the type.