Zod Transform and Coerce Pipeline

Coerce and transform incoming strings inside a Zod schema so trimming, defaults, and type conversion happen in one validated step.

TypescriptData Integrity

Code

typescriptsnippet
22 lines
import { z } from "zod";

export const QuerySchema = z.object({
  page: z.coerce.number().int().min(1).catch(1),
  pageSize: z.coerce.number().int().min(1).max(100).default(20),
  tags: z
    .string()
    .transform((raw) => raw.split(",").map((s) => s.trim()).filter(Boolean))
    .pipe(z.array(z.string().min(1)).max(10)),
  sort: z.enum(["asc", "desc"]).default("asc"),
});

export type Query = z.infer<typeof QuerySchema>;

export function parseQuery(params: Record<string, string | undefined>) {
  return QuerySchema.parse({
    page: params.page,
    pageSize: params.pageSize,
    tags: params.tags ?? "",
    sort: params.sort,
  });
}

How the code works

Zod Transform and Coerce Pipeline is built around the function parseQuery.

Reach for zod and what you get is z — that is the whole API contact area.

Caveats

  • Plan for an install step: zod is a real dependency, resolved by the package manager.

Applying it

The primary signature is export const QuerySchema =

QuerySchema is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

return QuerySchema.parse({
  page: params.page,
  pageSize: params.pageSize,
  tags: params.tags ?? "",
  sort: params.sort,
});
.transform((raw) => raw.split(",").map((s) => s.trim()).filter(Boolean))
.pipe(z.array(z.string().min(1)).max(10)),
sort: z.enum(["asc", "desc"]).default("asc"),
});

Interactive Tools for This Topic

FAQ

Which packages must be installed first?
Yes. The imports resolve to `zod`, which the package manager must provide.