1. TypeScript in Express

Vanilla Express routes accept req and res as any. That means you can typo a property name, access the wrong field on req.body, or forget a required parameter — and JavaScript will silently let it through until runtime. TypeScript changes that.

The @types/express package ships type definitions for Express. Once installed, every Request and Response object is fully typed.

🛒
UrbanCart Example
Typed product route handler

UrbanCart's Express API serves product data, handles orders, and processes payments. Without types, a developer could accidentally read req.body.productId as a number when it arrives as a string. With TypeScript, the compiler catches that mismatch before deployment.

routes/products.ts Typed Request & Response
TypeScript compiler output — before fixing types
routes/products.ts:31:22 - error TS2345: Argument of type 'string | undefined' is not assignable to parameter of type 'string'. 31 const product = await db.products.create({ name, price }); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Type 'undefined' is not assignable to type 'string'. Found 1 error. Fix it by ensuring all required fields are present.

Extending Express.Request for req.user

The most common real-world requirement is attaching the authenticated user to every request. After your auth middleware runs, you want req.user to be available — typed correctly — in every downstream handler. TypeScript doesn't know about req.user by default, so you use declaration merging to add it.

types/express.d.ts Declaration Merging — extending Express.Request
Declaration merging: TypeScript allows you to "reopen" an interface and add properties to it. By targeting Express.Request inside declare global, you extend the type that every Express route handler sees — without modifying the library source.
middleware/auth.ts Typed auth middleware
tsc — catching a common mistake
middleware/auth.ts:28:22 - error TS2532: Object is possibly 'undefined'. 28 const userId = req.user.id; ~~~~~~~~~~ Fix: use non-null assertion (req.user!.id) only after requireAuth middleware, or narrow with: if (req.user) { ... }

2. tsconfig.json

The tsconfig.json file controls how TypeScript compiles your project. It lives in the root of your project and is read by tsc, ts-node, and frameworks like Next.js automatically.

tsconfig.json Next.js project configuration
Option What it does Recommended
target JavaScript version to emit. ES2020 for Node 18+, ES5 for legacy browser support. ES2020
module Module format of emitted code. CommonJS for Node, ESNext for bundlers. CommonJS (Node)
strict Enables all strict type-checking flags at once. The most important option. true always
outDir Where compiled .js files are written. ./dist
rootDir Root directory of TypeScript source files. ./src
paths Import path aliases. Cleaner imports, no more ../../../ hell. Project-specific
esModuleInterop Allows default imports from CommonJS modules. true
skipLibCheck Skip checking types in node_modules. Dramatically speeds up compilation. true
Next.js note: When you run create-next-app --typescript, Next.js generates a tsconfig.json for you. The key differences from a plain Node project: module is set to ESNext, jsx is set to preserve (Next.js handles JSX), and incremental is true for faster re-builds.

3. Before / After — JS to TS Conversion

Converting an existing Express route from JavaScript to TypeScript is mostly mechanical: rename the file, add type annotations, and let the compiler point you to the gaps. Here's a real-world UrbanCart example.

⚠ Before — JavaScript (routes/orders.js)
✓ After — TypeScript (routes/orders.ts)
tsc catches these issues immediately on conversion
routes/orders.ts:41:7 - error TS2739: Type '{ userId: string; items: OrderItem[]; total: number; couponCode: string | undefined; }' is missing the following properties from type 'OrderCreateInput': createdAt 41 const order = await db.orders.create({ ~~~~~ routes/orders.ts:22:33 - error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'. (price: string from untyped req.body) Found 2 errors.
Conversion strategy: Rename .js to .ts. Start with // @ts-nocheck at the top to get it compiling, then remove it and fix errors one by one. The compiler becomes your to-do list.

4. TypeScript in Next.js

Next.js has first-class TypeScript support. The framework ships its own types for pages, API routes, middleware, and Server Actions. You get autocomplete for params, type errors for missing props, and typed request/response objects throughout.

Typed Page Components (PageProps)

In Next.js 13+ App Router, every page component receives params and searchParams as props. The PageProps pattern types these precisely.

app/products/[slug]/page.tsx Typed page component with dynamic params

Typed API Route Handlers

Next.js 13+ API routes use NextRequest and NextResponse instead of the old Express-style req/res objects.

app/api/products/[id]/route.ts Typed API route handler

Typed Server Actions

Server Actions are async functions that run on the server — called directly from client components. With TypeScript, you can type their parameters, return values, and error states precisely.

app/actions/cart.ts Typed Server Action — add to cart
TypeScript enforcing the discriminated union
app/checkout/page.tsx:44:28 - error TS2339: Property 'data' does not exist on type 'ActionResult<CartItem>'. Property 'data' does not exist on type '{ success: false; error: string; }'. 44 const itemId = result.data.id; ~~~~ Fix: narrow first: if (result.success) { console.log(result.data.id); }

5. Common Patterns — Zod, satisfies, as const

Three TypeScript patterns appear constantly in production Next.js and Node codebases. Understanding them makes reading real-world code much easier.

Zod — Runtime Validation

TypeScript's types disappear at runtime. If an external API sends you malformed JSON, or a form submits unexpected data, TypeScript can't help. Zod validates data shapes at runtime and infers TypeScript types from the schema — so you write the definition once.

lib/schemas/product.ts Zod schema for UrbanCart product
Zod validation output — catching bad data at runtime
ZodError: [ { "code": "too_small", "minimum": 0, "type": "number", "inclusive": true, "message": "Stock cannot be negative", "path": ["stock"] }, { "code": "invalid_string", "validation": "url", "message": "Invalid url", "path": ["imageUrl"] } ]

The satisfies Operator

Introduced in TypeScript 4.9, satisfies validates that a value matches a type without widening its inferred type. This preserves literal types and enables better autocomplete.

lib/config/routes.ts satisfies — preserving literal types

as const — Immutable Literal Types

lib/constants.ts as const — literal union types
🔷

Zod vs TypeScript

TypeScript checks types at compile time. Zod checks shapes at runtime. Use both: TypeScript for your own code, Zod for external data (API responses, form inputs, environment variables).

✅

satisfies vs : Type

: RouteConfig[] widens the type. satisfies RouteConfig[] validates the shape but keeps the narrowest inferred type. Use satisfies for config objects and constant declarations.

6. Type-safe Environment Variables

By default, process.env.ANYTHING is typed as string | undefined in TypeScript. This means you get no autocomplete on variable names, no error if you misspell DATABASE_URL, and no warning if a required variable is missing. Declaration merging fixes this.

types/env.d.ts Typed process.env via declaration merging
How it works: ProcessEnv lives in the NodeJS namespace. By declaring it inside declare global { namespace NodeJS { ... } }, TypeScript merges your additions into the existing interface. Now process.env.DATABASE_URL is typed as string (not string | undefined), and typos like process.env.DATABASE_URLS become a compile error.
lib/env.ts Runtime validation of required env vars with Zod
Startup error when required variables are missing
❌ Invalid environment variables: { DATABASE_URL: [ 'Required' ], JWT_SECRET: [ 'JWT secret must be at least 32 chars' ], STRIPE_SECRET_KEY: [ 'Required' ] } Process exited with code 1.
Type Safety — Three Layers
TypeScript
Compile-time checks
+
Zod
Runtime validation
+
Declaration merging
Typed env & req.user

Quiz

Question 1 of 5
How do you add a custom property like user to Express's Request type?
Question 2 of 5
What does strict: true in tsconfig.json enable?
Question 3 of 5
What is Zod used for in a TypeScript project?
Question 4 of 5
How do you type Next.js page props when the route has a dynamic segment like [slug]?
Question 5 of 5
What is the satisfies operator in TypeScript?
0
/ 5
Great job!

You completed the TypeScript with Node & Next.js quiz.

Next Lesson

JavaScript Cheatsheet →
You've completed the Full Stack track! Check out the cheatsheets and interview prep.
Africa & India's Best AI Academy
🤖 AI-first 🎓 Placement Assistance

You just typed a full-stack app end to end.
Now build a career with the same precision.

Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.

Explore our AI-era courses →