Zod: Parse, Don't Validate (Dates That Aren't Dates, Numbers That Are Strings)
- Published
- Duration
- Language
- English
Summary
TypeScript types do not exist at runtime, so `JSON.parse(body) as Order` checks nothing. This short explainer shows three failures that type-check (a date that arrives as a string, new Date("garbage") returning an Invalid Date, and "10" + 5 giving "105") and how parsing once at the boundary with a Zod 4 schema and safeParse gives typed, trusted data and a clean error before any side effect runs.
Caveat: z.coerce.number() turns "" into 0 and z.coerce.boolean() turns "false" into true. Prefer explicit validators such as z.iso.datetime() and z.stringbool() where that matters.
Examples run with zod 4.6.7, TypeScript 7.0.2, Node 20.
Transcript
Text of the video's narration.
TypeScript types do not exist at runtime, so casting parsed JSON to a type checks nothing. Here, the quantity arrives as the string ten. TypeScript says it is a number, and ten plus five gives one hundred five, as text. The shipping date arrives as a string too, so calling getTime throws.
And the Date constructor does not fail on garbage. It quietly returns an Invalid Date. The fix is to parse once, at the boundary. Define a Zod schema: a positive integer quantity, and an ISO datetime string that becomes a real Date.
Then call safeParse on the unknown input. If it fails, you get a clean error with the field and the reason, before the payment, the database write, or the email runs. If it passes, the result is typed from the schema, and the rest of your app can trust it.
One caveat. Coerce number turns an empty string into zero, and coerce boolean turns the string false into true. For query parameters, check the format first, or use explicit validators. Parse, don't validate. Alexis King wrote that up in 2019.
Sources
- Zod: Defining schemas (coerce, iso, stringbool, codecs) zod.dev
- Zod: Basic usage (safeParse) zod.dev
- Alexis King, "Parse, don't validate" (2019) lexi-lambda.github.io
- Zod on GitHub github.com
Credits and notes
- Narrated with Phonon; motion in Remotion.



