Zod infer vs TypeScript Interfaces: Runtime Validation Gaps
An interface validates nothing, z.infer is the output type and not the input, and Zod 4 renamed the error helpers. What each one actually guarantees.

Introduction & Quick Summary
Symptom. A fetch response cast with as User renders undefined everywhere in production, and TypeScript reports no error at all. Or a Zod schema with .default() and .transform() compiles against z.infer but the function's parameter rejects the object the form actually sends. Or the error handler crashes on `result.error.format is not a function after moving to Zod 4.
Cause. A TypeScript interface is erased at compile time: as User is an assertion about a value nobody checked, so a missing field is typed as string and is undefined at runtime. z.infer<typeof S> is the output type, after defaults, transforms, and coercions; the value the caller passes in is z.input<typeof S>, which can differ in optionality and in type. And Zod 4 replaced the error-formatting helpers: .format() and .flatten() on the error object are gone in favour of the top-level z.treeifyError() and z.flattenError().
Fix. Derive the type from the schema, not beside it; use z.input<> for parameters that receive unvalidated data and z.infer<> for values that have passed parse; and format failures with the Zod 4 helpers (or pin Zod 3 and accept the deprecation).
Core Mechanics, Signatures & Reproducible Setup
A schema and an interface written separately drift, and the drift is invisible because both compile.
// drift-prone: two declarations of the same shape
interface User { id: string; email: string; createdAt: Date }
const UserSchema = z.object({ id: z.string(), email: z.string().email() });
// createdAt is missing from the schema; every User is a lie about one field// single source of truth
const UserSchema = z.object({
id: z.string().uuid(),
email: z.string().email(),
createdAt: z.coerce.date(),
role: z.enum(["admin", "member"]).default("member"),
});
type User = z.infer<typeof UserSchema>; // output: role required
type UserInput = z.input<typeof UserSchema>; // input: role optionalThat default is the whole input/output distinction. z.infer says role: "admin" | "member"; z.input says role?: "admin" | "member" | undefined. A function typed (u: User) => void rejects a form payload, and the error names role without explaining that the schema supplies it.
To keep a hand-written interface — for a generated API client, or a class — assert the schema against it once, and let the compiler fail when they diverge:
type Checked = z.ZodType<UserDto, UserDto>;
const schema: Checked = UserSchema; // errors if either direction driftsReproduce the unchecked-assertion bug with two lines and no network:
const data = JSON.parse('{"id": 1}') as User; // compiles
console.log(data.email.toLowerCase()); // TypeError at runtimeKey Comparison Table
| Aspect | TypeScript interface | Zod schema |
|---|---|---|
| Exists at runtime | no | yes |
| Rejects bad input | never | on parse / safeParse |
| Produces the type | is the type | z.infer / z.input |
| Unknown keys | ignored by TS | stripped by z.object, rejected by z.strictObject |
| Transform / default | impossible | built in, changes input vs output type |
| Bundle cost | zero | roughly 12–14 kB min+gzip for the core |
| Zod 3 | Zod 4 | Note |
|---|---|---|
error.format() | z.treeifyError(error) | nested tree keyed by path |
error.flatten() | z.flattenError(error) | fieldErrors and formErrors |
z.string().email() | z.email() | string-format methods split off |
.strict() | z.strictObject({…}) | .strict() deprecated |
.passthrough() | z.looseObject({…}) | same rename family |
z.infer only | z.infer and z.input | input type is first-class |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
1. safeParse return shape
safeParse returns a discriminated union, so success is the narrowing key and data exists only on the true branch.
const result = UserSchema.safeParse(payload);
if (!result.success) {
return { status: 400, body: z.flattenError(result.error).fieldErrors };
}
const user = result.data; // typed, defaulted, transformedAccessing result.data before checking success is undefined at runtime and a type error under strict. parse throws ZodError, which is right at a boundary you do not control and wrong inside a request handler that must return 400.
2. Formatting errors for a form versus a log
z.flattenError gives one level of field errors, which is what a form needs. z.treeifyError preserves nesting for array and object fields.
const flat = z.flattenError(result.error);
// { formErrors: [], fieldErrors: { email: ["Invalid email"], "tags.0": ["Too short"] } }
const tree = z.treeifyError(result.error);
// { errors: [], properties: { email: { errors: [...] }, tags: { items: [...] } } }An array field's errors live under items, not under the field name, which is why a form built on flatten shows "Invalid input" with no path for tags[0]. Zod's issues array remains the ground truth: each entry has path, code, and message.
3. Discriminated unions instead of z.union
z.union tries each member in order and reports every branch's failure. z.discriminatedUnion reads the tag first, so it is faster and its error names one branch.
const Event = z.discriminatedUnion("type", [
z.object({ type: z.literal("click"), x: z.number(), y: z.number() }),
z.object({ type: z.literal("key"), key: z.string() }),
]);The tag must be a literal in every member. A z.string() tag silently degrades the union to a slow scan, and the error becomes the unreadable "Invalid input" of the whole union.
4. as at the network boundary is the actual bug
Every unvalidated cast is a promise the runtime never made. Three patterns replace it without a full rewrite:
const raw: unknown = await res.json(); // unknown, not any
const parsed = UserSchema.parse(raw); // throws on drift
// or, when partial data is acceptable:
const loose = UserSchema.partial().parse(raw);Typing the fetch helper's return as Promise<unknown> forces every call site to choose. satisfies User is still a compile-time check and belongs only where the value is constructed in code, not parsed from text.
5. z.infer on a transformed schema
.transform() makes input and output different types, and TypeScript will not tell you which one a generic wants.
const Query = z.object({ page: z.string() }).transform((v) => ({ page: Number(v.page) }));
type QueryIn = z.input<typeof Query>; // { page: string }
type QueryOut = z.infer<typeof Query>; // { page: number }A route handler that validates search params takes QueryIn from the framework and passes QueryOut inward. Mixing them produces Argument of type '{ page: string }' is not assignable to parameter of type '{ page: number }' — a correct error about a real boundary.
6. One schema for client and server
Sharing a schema across the boundary works only if the schema has no server-only side effects and no File, Buffer, or Node API. Keep transforms pure, and put environment-dependent rules in a second schema built on superRefine.
Common Compilation/Runtime Mistakes & Version Gotchas
interfaceplusz.inferboth declared. They drift; pick the schema and derive.z.inferused for input. With defaults or transforms this rejects valid payloads; usez.input..optional()versus.default(). Optional leaves the key absent; default fills it and removesundefinedfrom the output type.z.objectstrips unknown keys. Data silently disappears; usez.strictObjectto reject,z.looseObjectto keep..strict()and.passthrough()are deprecated in Zod 4..format()on a Zod 4 error. Removed;z.treeifyErrororz.flattenErrorinstead.z.string().email()in Zod 4. Deprecated in favour ofz.email(); still works through a compat shim but the type surface changed.anyin a generic schema.z.ZodType<any>disables inference for every consumer; preferz.ZodType<Output, Input>.
Related tools. Turn a captured API response into a candidate interface before writing the schema with the JSON to TypeScript converter, normalise the JSON error body so field paths are readable with the JSON formatter, and check that a payload survives the round trip between client and server with the CSV to JSON converter.
Try matching browser tools
All toolsSmall utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related TypeScript guides
All TypeScript guidesTypeScript Decorators: Standard vs experimentalDecorators
TS1240 appears when a legacy decorator meets the stage 3 transform, and the reverse breaks NestJS DI. How the two signatures differ and which flag each stack needs.
TS2307 and TS2835: Cannot Find Module Under moduleResolution NodeNext
NodeNext models Node's real resolution, so .js belongs in the source import and exports maps decide what exists. Why bundler resolution hides both errors.
TypeScript strict Mode: TS2531, TS7006, and TS18047 Migrations
strict is nine flags at once. Count errors per code, fix them in the order that keeps the build green, and narrow instead of asserting.
TypeScript Generic Parameter Defaults: Syntax, Precedence, and Inference
When a default applies and when inference wins, defaults that reference earlier parameters, and how a defaulted type parameter keeps a library change non-breaking.
More in TypeScript
All TypeScript guidesThe guides filed next to this one in TypeScript, in library order.