What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
TypeScript checks your code before it runs; it does not verify that an API response, request body, queue message, or stored record matches the type you assigned it. Validate external values at the boundary where your application begins to trust them. With Zod, a schema can check the value at runtime and provide the TypeScript type for validated data.
Why TypeScript types do not prevent bad runtime data
TypeScript’s types are removed during compilation. They help catch inconsistencies in your program, but they do not inspect values delivered at runtime. As the TypeScript Handbook explains, “A type assertion is like a type cast in other languages, but it performs no special checking or restructuring of data.” It has no runtime impact.
That is why this does not validate an API response:
const user = payload as User;
The assertion tells the compiler to treat payload as a User. If the payload is missing an ID or contains an unexpected value, the assertion does nothing to correct or reject it. Instead, treat data you have not checked as unknown, and validate it before passing it into code that relies on a particular shape.
#1 Best Overall
Where to put runtime validation
Validate at trust boundaries: the points where data enters a component whose logic assumes specific fields, formats, or values. This applies to incoming data from users and to data arriving from systems you operate. A service’s internal status does not guarantee that its messages are current or well-formed.
- HTTP requests: Validate on the server before business logic uses request data. Client-side validation can improve usability, but it does not replace server-side checks.
- HTTP responses: Validate third-party API data before relying on its fields, nested values, or enumerated choices.
- Queues and partner feeds: Check each message when a consumer takes responsibility for it, even if a producer is another internal service.
- Storage: Validate records when reading them into a component that expects a particular contract. Stored data may be stale or malformed.
- Browser messages: Validate values received across message boundaries before treating them as application data.
OWASP’s guidance recommends validating untrusted input early in the data flow. The practical boundary is not simply “the internet”: it is wherever data becomes an assumption in your code.
Validate an API response with a Zod schema
Define the expected structure once, parse the untrusted value, and infer the application type from that schema. The following example uses Zod 4’s documented API:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Rank #2
- TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
- TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
- Lightweight, Classic fit, Double-needle sleeve and bottom hem
import * as z from "zod";
const UserSchema = z.object({
id: z.string(),
email: z.email(),
age: z.number().int().nonnegative(),
});
type User = z.infer<typeof UserSchema>;
async function loadUser(response: Response): Promise<User> {
const input: unknown = await response.json();
return UserSchema.parse(input);
}
The schema checks that id is a string, email has the required email format, and age is a nonnegative integer. If the value passes, parse() returns data matching the schema and the inferred User type. If it does not, Zod throws a ZodError.
This example’s parsing call can also fail before Zod receives a value: response.json() may reject if the response body cannot be decoded as JSON. Handle that decoding failure in the application’s error path as well. A Zod schema validates the value produced by the parser; it does not replace the parser.
Choose between parse and safeParse
Both methods validate against the schema. Choose based on how the surrounding code should handle invalid input.
| Method | Invalid input | Use it when |
|---|---|---|
parse() |
Throws a ZodError. |
The surrounding error-handling path should handle validation failure as an exception. |
safeParse() |
Returns a discriminated result containing either validated data or an error. |
Invalid input is an expected branch that the caller should handle explicitly. |
For example, a request handler can branch on a failed result and stop before invalid data reaches application logic:
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsconst result = UserSchema.safeParse(input);
if (!result.success) {
// Return an appropriate client error, discard the message,
// or record safe metadata. Do not use invalid data.
return;
}
const user = result.data;
For schemas with asynchronous refinements or transforms, use parseAsync() or safeParseAsync(); the synchronous methods are not appropriate for asynchronous schema work.
Check business meaning, not just data shape
A structurally valid value can still violate the rules of the operation. Two dates can each be valid dates while the end date precedes the start date. A number can be an integer but fall outside an allowed range. Validate those semantic conditions alongside field types and formats, using schema refinements or other checks close to the boundary.
- Require the fields the receiving component actually needs.
- Constrain formats, ranges, and allowed choices rather than accepting any string or number.
- Check relationships between fields, such as date ordering or related totals.
- For nested objects and arrays, define the expected nested schemas and validate every item.
- Set sensible field and array-size limits where the contract calls for them.
Decide what happens to unknown object keys
Zod object schemas strip unrecognized keys by default. A strict object rejects unknown keys; a loose object preserves them. This is a contract decision, not a universally correct security setting. Consider whether the receiver should silently ignore extra fields, treat them as an error, or pass them through. Make the choice deliberately, especially when schemas sit between independently evolving services.
Use coercion only when conversion is part of the contract
A coercion schema such as z.coerce.number() applies JavaScript number conversion to its input. That conversion does not establish that the original input was acceptable for your application. Use coercion only when the input contract intentionally permits conversion, then constrain the result with meaningful checks—for example, require an integer and an allowed range where appropriate.
Free tools Windows power users keep installed
One-click scans. No signup required.
Handle failures without creating new risks
When validation fails, stop the value from flowing into code that assumes it is valid. Return useful, limited feedback where appropriate, but do not expose sensitive internals or log full request bodies that may contain secrets. Record only the metadata needed for diagnosis under your application’s logging practices.
Best Value
Validation also comes after parsing in the common JSON workflow. A schema cannot protect a parser that has already buffered an excessively large body or spent too many resources decoding it. Apply request-size and parser-depth limits before expensive parsing where your framework allows it, then validate the parsed value.
What Zod validation does not replace
Passing a schema means the value satisfies the checks in that schema; it does not mean every use of that value is safe or permitted. Use the control appropriate to the operation and destination:
- Authorization: Check whether the caller may perform the requested action on the specific resource.
- Database access: Use parameterized queries rather than inserting input into SQL strings.
- HTML output: Apply context-appropriate output encoding.
- Commands, paths, and redirects: Apply destination-specific restrictions; a valid string may still be an unsafe command argument, file path, or redirect target.
- Rich content and files: Use the separate sanitization, parsing, and file-handling controls appropriate to those formats.
Zod and TypeScript compatibility
The official Zod documentation describes Zod 4 as stable, identifies zod/v4 as its flagship package, and states that it is tested against TypeScript 5.5 and later and requires TypeScript’s strict mode. Check the Zod 4 documentation for the current compatibility and API details when setting up or upgrading a project.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

