Lesson 114 of 296
Zod and tsconfig
What you will learn
- Why runtime validation is needed
- Zod schemas, parse and safeParse
- Getting TypeScript types from schemas
- A typed fetch wrapper that validates responses
- The important tsconfig settings
On this page
Why runtime validation?
TypeScript types are erased (Lesson 99). Data from outside your code (API responses, request bodies, form input, environment variables, files, localStorage) can be anything. Writing as User does not make it a user.
Validate data at the boundaries of your system, where it enters. After validation, TypeScript types are trustworthy everywhere inside.
Zod
Zod is a popular TypeScript-first validation library. You describe the shape once as a schema. Zod checks data at runtime, and TypeScript gets the type from the same schema. (This lesson uses Zod 4's API. Other libraries with similar ideas include Valibot and ArkType.)
npm install zodimport { z } from "zod";
const UserSchema = z.object({
id: z.number().int().positive(),
name: z.string().min(1),
email: z.email(),
role: z.enum(["admin", "user"]),
age: z.number().int().optional()
});
type User = z.infer<typeof UserSchema>;z.infer produces:
{ id: number; name: string; email: string; role: "admin" | "user"; age?: number | undefined }One source of truth: the schema. The type can never drift away from the validation.
parse and safeParse
parse returns the data if it is valid, and throws a ZodError if not:
const user = UserSchema.parse(unknownData);safeParse never throws. It returns a result object (a discriminated union, Lesson 107):
const result = UserSchema.safeParse(unknownData);
if (!result.success) {
console.error(result.error.issues); a list of what is wrong and where
} else {
console.log(result.data.name); result.data: User
}Use safeParse when you want to show validation errors to users (forms, API request bodies); parse when invalid data is a real error.
Useful schema features
| Feature | Example |
|---|---|
| Strings | z.string().min(8).max(100), z.email(), z.url(), z.uuid() |
| Numbers | z.number().int().min(0) |
| Optional / nullable | .optional(), .nullable() |
| Defaults | z.number().default(1) |
| Enums | z.enum(["sm", "md", "lg"]) |
| Arrays | z.array(UserSchema) |
| Discriminated unions | z.discriminatedUnion("status", [...]) |
| Converting input | z.coerce.number() turns "42" into 42 (useful for query strings and forms) |
| Custom rules | .refine((v) => v.end > v.start, { message: "End must be after start" }) |
A typed fetch wrapper with Zod
A task from the study plan:
import { z } from "zod";
class HttpError extends Error {
constructor(public status: number, message: string) {
super(message);
this.name = "HttpError";
}
}
async function fetchJson<T>(
url: string,
schema: z.ZodType<T>,
init?: RequestInit
): Promise<T> {
const response = await fetch(url, init);
if (!response.ok) {
throw new HttpError(response.status, `Request to ${url} failed`);
}
const body: unknown = await response.json();
return schema.parse(body);
}
const OrdersSchema = z.array(
z.object({
id: z.string(),
totalPence: z.number().int(),
status: z.enum(["pending", "paid", "shipped"])
})
);
const orders = await fetchJson("/api/orders", OrdersSchema);
orders[0]?.status; "pending" | "paid" | "shipped"How it works:
Tis inferred from the schema you pass, so the return type is automatic.- The JSON body is typed
unknownuntil it passesschema.parse. - If the server ever sends the wrong shape, you get a clear validation error at the boundary, instead of a confusing crash deep in your UI.
public statusin the constructor is a TypeScript shortcut that creates and assigns a property.
On the server (Parts 15 and 16), the same idea validates request bodies and environment variables at startup.
tsconfig.json
tsconfig.json configures the compiler. A typical modern setup:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022", "DOM"],
"strict": true,
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist",
"rootDir": "src",
"baseUrl": ".",
"paths": { "@/*": ["src/*"] }
},
"include": ["src"]
}| Option | Meaning |
|---|---|
target | Which JavaScript version to output, such as ES2022 |
module | Which module system to output (Lesson 73) |
moduleResolution | How imports are found. NodeNext for Node.js projects, Bundler for apps built with Vite, Next.js and similar |
lib | Which built-in types exist: DOM for browser code, ES versions for language features |
strict | All strict checks (Lesson 105). Always on. |
noUncheckedIndexedAccess | Index access includes undefined |
esModuleInterop | Smoother imports of CommonJS packages |
skipLibCheck | Skip type-checking .d.ts files in node_modules: faster builds |
outDir / rootDir | Where output goes / where source lives |
paths | Import aliases, such as @/components/Button instead of ../../components/Button |
noEmit | Only check types, output nothing (when a bundler builds the code) |
jsx | How to handle JSX, such as react-jsx or preserve |
isolatedModules / verbatimModuleSyntax | Make sure each file can be compiled alone, which fast build tools require |
Frameworks such as Next.js and NestJS create a suitable tsconfig.json for you. You should still be able to explain the main options.
paths only affects TypeScript's type checking. The bundler or runtime must also understand the alias (most frameworks configure this automatically).
Common mistakes
- Trusting API data because "it has a type".
- Writing a type and a schema separately so they drift apart. Use
z.infer. - Using
parsewhere a failure should show friendly form errors (usesafeParse). - Turning off
strict. - Copying a tsconfig without understanding
moduleandmoduleResolution, then fighting import errors.
How to say it in an interview
"Because types are erased, I validate untrusted data at the boundaries, such as API responses, request bodies and environment variables. With Zod I define a schema once and derive the type with z.infer, so validation and types cannot drift. parse throws on invalid data, safeParse returns a success-or-error result for user-facing validation. My fetch wrapper types the JSON as unknown, validates it with the schema passed in, and infers the return type from it. In tsconfig I always enable strict, choose module and moduleResolution to match Node or the bundler, set lib for the environment, and use paths for clean imports."
Key words
| Word | Meaning |
|---|---|
| Runtime validation | Checking data while the program runs |
| Boundary | Where external data enters your system |
| Schema | A description of the expected shape of data |
| Zod | A TypeScript-first validation library |
| z.infer | Gets a TypeScript type from a Zod schema |
| parse / safeParse | Validate and throw / validate and return a result |
| tsconfig.json | The TypeScript compiler's configuration file |
| Path alias | A short import path such as @/utils |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.