Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~1 min readTypeScript
#TypeScript#Zod#Validation#API
3D illustration of a schema cube with a runtime shield overlapping a hollow type-only wireframe cube, error issue tags floating off

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.

ts
// 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
ts
// 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 optional

That 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:

ts
type Checked = z.ZodType<UserDto, UserDto>; const schema: Checked = UserSchema; // errors if either direction drifts

Reproduce the unchecked-assertion bug with two lines and no network:

ts
const data = JSON.parse('{"id": 1}') as User; // compiles console.log(data.email.toLowerCase()); // TypeError at runtime

Key Comparison Table

AspectTypeScript interfaceZod schema
Exists at runtimenoyes
Rejects bad inputneveron parse / safeParse
Produces the typeis the typez.infer / z.input
Unknown keysignored by TSstripped by z.object, rejected by z.strictObject
Transform / defaultimpossiblebuilt in, changes input vs output type
Bundle costzeroroughly 12–14 kB min+gzip for the core
Zod 3Zod 4Note
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 onlyz.infer and z.inputinput 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.

ts
const result = UserSchema.safeParse(payload); if (!result.success) { return { status: 400, body: z.flattenError(result.error).fieldErrors }; } const user = result.data; // typed, defaulted, transformed

Accessing 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.

ts
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.

ts
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:

ts
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.

ts
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

  • interface plus z.infer both declared. They drift; pick the schema and derive.
  • z.infer used for input. With defaults or transforms this rejects valid payloads; use z.input.
  • .optional() versus .default(). Optional leaves the key absent; default fills it and removes undefined from the output type.
  • z.object strips unknown keys. Data silently disappears; use z.strictObject to reject, z.looseObject to keep. .strict() and .passthrough() are deprecated in Zod 4.
  • .format() on a Zod 4 error. Removed; z.treeifyError or z.flattenError instead.
  • z.string().email() in Zod 4. Deprecated in favour of z.email(); still works through a compat shim but the type surface changed.
  • any in a generic schema. z.ZodType<any> disables inference for every consumer; prefer z.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 tools

Small utilities that fit TypeScript work — they run entirely in this browser tab, so nothing you paste leaves your device.

All TypeScript guides

More in TypeScript

All TypeScript guides

The guides filed next to this one in TypeScript, in library order.