Skip to the content

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 zod
import { 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

FeatureExample
Stringsz.string().min(8).max(100), z.email(), z.url(), z.uuid()
Numbersz.number().int().min(0)
Optional / nullable.optional(), .nullable()
Defaultsz.number().default(1)
Enumsz.enum(["sm", "md", "lg"])
Arraysz.array(UserSchema)
Discriminated unionsz.discriminatedUnion("status", [...])
Converting inputz.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:

  • T is inferred from the schema you pass, so the return type is automatic.
  • The JSON body is typed unknown until it passes schema.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 status in 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"]
}
OptionMeaning
targetWhich JavaScript version to output, such as ES2022
moduleWhich module system to output (Lesson 73)
moduleResolutionHow imports are found. NodeNext for Node.js projects, Bundler for apps built with Vite, Next.js and similar
libWhich built-in types exist: DOM for browser code, ES versions for language features
strictAll strict checks (Lesson 105). Always on.
noUncheckedIndexedAccessIndex access includes undefined
esModuleInteropSmoother imports of CommonJS packages
skipLibCheckSkip type-checking .d.ts files in node_modules: faster builds
outDir / rootDirWhere output goes / where source lives
pathsImport aliases, such as @/components/Button instead of ../../components/Button
noEmitOnly check types, output nothing (when a bundler builds the code)
jsxHow to handle JSX, such as react-jsx or preserve
isolatedModules / verbatimModuleSyntaxMake 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 parse where a failure should show friendly form errors (use safeParse).
  • Turning off strict.
  • Copying a tsconfig without understanding module and moduleResolution, 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

WordMeaning
Runtime validationChecking data while the program runs
BoundaryWhere external data enters your system
SchemaA description of the expected shape of data
ZodA TypeScript-first validation library
z.inferGets a TypeScript type from a Zod schema
parse / safeParseValidate and throw / validate and return a result
tsconfig.jsonThe TypeScript compiler's configuration file
Path aliasA short import path such as @/utils

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.