JavaScript and TypeScript course ยท Module 10: TypeScript in Practice
TypeScript with Node.js - Practical Patterns
In this lesson5
When you manage the infrastructure of Jurassic Park, you need a reliable backend: an authorization system, an API for managing zones and middleware for logging. A single handler that accepts dangerLevel as text instead of a number can break the security report of the whole park. TypeScript combined with Node.js and Express lets you build servers with full type safety and eliminate entire classes of bugs before you run the code.
Typing Routes in Express
By default, req.body has the type any in Express, req.query is a generic ParsedQs dictionary, and req.params is a dictionary of strings. We narrow them with the generic Request<Params, ResBody, ReqBody, Query>, where the order of parameters matters. First we describe the API data:
import { Request, Response, NextFunction, Router } from 'express';
// Interfaces for our API data
interface Dinosaur {
id: string;
species: string;
diet: 'herbivore' | 'carnivore' | 'omnivore';
zone: string;
weight: number;
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
// Typed Request - params, body, query
interface GetDinosaurParams {
id: string;
}
interface ListDinosaursQuery {
zone?: string;
diet?: Dinosaur['diet'];
limit?: string;
offset?: string;
}
interface CreateDinosaurBody {
species: string;
diet: Dinosaur['diet'];
zone: string;
weight: number;
dangerLevel: Dinosaur['dangerLevel'];
}Dinosaur['diet'] is an indexed access type: it takes the type of a field from another interface, so the list of diets exists in only one place. limit and offset are strings, because that is how they arrive in the URL.
Now a handler with typed path parameters. The first Request generic describes params, and Response<T> guards the shape of the response:
// Typed handlers
const router = Router();
// GET /dinosaurs/:id - typed params
router.get('/dinosaurs/:id',
(req: Request<GetDinosaurParams>, res: Response<Dinosaur | { error: string }>) => {
const dinoId: string = req.params.id; // typed!
// req.params.name; // Compilation error - no "name" in params
const dinosaur: Dinosaur = {
id: dinoId,
species: 'Velociraptor',
diet: 'carnivore',
zone: 'B-7',
weight: 80,
dangerLevel: 4
};
res.json(dinosaur);
}
);Referring to req.params.name is a compilation error, and res.json() accepts only a dinosaur or an error object.
We describe the query and body with further generics, putting {} and any in the positions we do not need:
// GET /dinosaurs - typed query
router.get('/dinosaurs',
(req: Request<{}, any, any, ListDinosaursQuery>, res: Response<Dinosaur[]>) => {
const zone = req.query.zone; // string | undefined
const diet = req.query.diet; // Dinosaur['diet'] | undefined
const limit = parseInt(req.query.limit || '10');
// Filtering based on typed query params
res.json([]);
}
);
// POST /dinosaurs - typed body
router.post('/dinosaurs',
(req: Request<{}, any, CreateDinosaurBody>, res: Response<Dinosaur>) => {
const body = req.body;
// body.species: string - typed!
// body.diet: 'herbivore' | 'carnivore' | 'omnivore' - typed!
// body.unknownField; // Compilation error
const newDinosaur: Dinosaur = {
id: 'DINO-' + Date.now(),
...body
};
res.status(201).json(newDinosaur);
}
);Remember that this is a promise, not validation: a client can send any JSON, so in production check the data at runtime, for example with the zod library. The type describes correct data, but it does not guarantee it.
Typing Middleware
Middleware in Express are functions that process a request before it reaches the handler. They receive req, res and next, and they break the chain by sending a response instead of calling next(). We extend the request interface with the data of the logged-in user:
// Middleware adding userId to request
interface AuthenticatedRequest extends Request {
userId: string;
role: 'visitor' | 'staff' | 'admin' | 'scientist';
}
function authMiddleware(
req: Request,
res: Response,
next: NextFunction
): void {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
res.status(401).json({ error: 'Missing authorization token' });
return;
}
// Token verification (simplified)
try {
const decoded = verifyToken(token); // Your verification function
(req as AuthenticatedRequest).userId = decoded.userId;
(req as AuthenticatedRequest).role = decoded.role;
next();
} catch (error) {
res.status(403).json({ error: 'Invalid token' });
}
}
// Helper declaration
declare function verifyToken(token: string): { userId: string; role: AuthenticatedRequest['role'] };
// Role-checking middleware
function requireRole(...roles: AuthenticatedRequest['role'][]) {
return (req: Request, res: Response, next: NextFunction): void => {
const authReq = req as AuthenticatedRequest;
if (!roles.includes(authReq.role)) {
res.status(403).json({
error: `Required role: ${roles.join(' or ')}`
});
return;
}
next();
};
}
// Usage in routes
router.delete('/dinosaurs/:id',
authMiddleware,
requireRole('admin', 'scientist'),
(req: Request, res: Response) => {
const authReq = req as AuthenticatedRequest;
console.log(`User ${authReq.userId} deleted dinosaur ${req.params.id}`);
res.status(204).send();
}
);So the order is: the request reaches the server, authMiddleware checks the token, requireRole verifies the role, and the handler receives the request after these checks. verifyToken returns a role of the type AuthenticatedRequest['role'], so the assignment is safe, and the as AuthenticatedRequest cast is your promise that the middleware ran earlier.
Typing Environment Variables
Environment variables (process.env) have the type string | undefined by default, because at compile time nobody knows whether they will be set. That is why we validate them when the application starts:
// Interface describing required environment variables
interface EnvironmentVariables {
NODE_ENV: 'development' | 'production' | 'test';
PORT: string;
DATABASE_URL: string;
JWT_SECRET: string;
PARK_NAME: string;
MAX_VISITORS: string;
ALERT_EMAIL: string;
}
// Function validating environment variables
function validateEnv(): EnvironmentVariables {
const required: (keyof EnvironmentVariables)[] = [
'NODE_ENV', 'PORT', 'DATABASE_URL', 'JWT_SECRET',
'PARK_NAME', 'MAX_VISITORS', 'ALERT_EMAIL'
];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
throw new Error(
`Missing environment variables: ${missing.join(', ')}`
);
}
return process.env as unknown as EnvironmentVariables;
}
// Usage - safe and typed
const env = validateEnv();
const port = parseInt(env.PORT); // string -> number
const dbUrl: string = env.DATABASE_URL; // definitely string, not undefined
const maxVisitors = parseInt(env.MAX_VISITORS);as unknown as is a double assertion with which you tell the compiler that you know better. The code checks that the variables exist, but not whether NODE_ENV has an allowed value, so add that test yourself. An application without a JWT secret will not start, instead of running with a hole in its security.
It is more convenient to wrap the configuration in a class that converts strings into numbers and booleans once:
// Alternatively - configuration class
class AppConfig {
readonly port: number;
readonly databaseUrl: string;
readonly jwtSecret: string;
readonly parkName: string;
readonly maxVisitors: number;
readonly isDevelopment: boolean;
constructor() {
const env = validateEnv();
this.port = parseInt(env.PORT);
this.databaseUrl = env.DATABASE_URL;
this.jwtSecret = env.JWT_SECRET;
this.parkName = env.PARK_NAME;
this.maxVisitors = parseInt(env.MAX_VISITORS);
this.isDevelopment = env.NODE_ENV === 'development';
}
}
// Singleton - single configuration instance
const config = new AppConfig();
console.log(`${config.parkName} starting on port ${config.port}`);You cannot overwrite readonly fields after the object is created. The mapped type Readonly<T>, written as { readonly [K in keyof T]: T[K] }, does the same for all fields at once.
Typing Configuration Objects
Complex configurations require deep typing. Each section gets its own interface, and AppConfiguration combines them:
// Database configuration
interface DatabaseConfig {
host: string;
port: number;
name: string;
credentials: {
username: string;
password: string;
};
pool: {
min: number;
max: number;
idleTimeout: number;
};
ssl: boolean;
}
// Server configuration
interface ServerConfig {
port: number;
host: string;
cors: {
origins: string[];
methods: ('GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH')[];
credentials: boolean;
};
rateLimit: {
windowMs: number;
max: number;
};
}
// Park configuration
interface ParkConfig {
zones: Record<string, {
name: string;
maxCapacity: number;
dangerLevel: number;
fenceVoltage: number;
}>;
alertThresholds: {
temperature: { min: number; max: number };
humidity: { min: number; max: number };
windSpeed: number;
};
}
// Full application configuration
interface AppConfiguration {
server: ServerConfig;
database: DatabaseConfig;
park: ParkConfig;
}
// Function loading configuration with validation
function loadConfiguration(): AppConfiguration {
return {
server: {
port: parseInt(process.env.PORT || '4000'),
host: process.env.HOST || '0.0.0.0',
cors: {
origins: (process.env.CORS_ORIGINS || 'http://localhost:3000').split(','),
methods: ['GET', 'POST', 'PUT', 'DELETE'],
credentials: true
},
rateLimit: {
windowMs: 15 * 60 * 1000,
max: 100
}
},
database: {
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT || '27017'),
name: process.env.DB_NAME || 'jurassic_park',
credentials: {
username: process.env.DB_USER || '',
password: process.env.DB_PASS || ''
},
pool: { min: 2, max: 10, idleTimeout: 30000 },
ssl: process.env.NODE_ENV === 'production'
},
park: {
zones: {
'zone-a': { name: 'Herbivore Zone', maxCapacity: 200, dangerLevel: 1, fenceVoltage: 5000 },
'zone-b': { name: 'Raptor Zone', maxCapacity: 50, dangerLevel: 5, fenceVoltage: 15000 },
'zone-c': { name: 'T-Rex Zone', maxCapacity: 30, dangerLevel: 5, fenceVoltage: 20000 }
},
alertThresholds: {
temperature: { min: -5, max: 45 },
humidity: { min: 20, max: 95 },
windSpeed: 120
}
}
};
}
// Usage
const appConfig = loadConfiguration();
console.log(`Park zones: ${Object.keys(appConfig.park.zones).length}`);
console.log(`Max raptor capacity: ${appConfig.park.zones['zone-b'].maxCapacity}`);A typo in a field name or a string instead of a number in fenceVoltage is a compilation error, not a fence failure at three in the morning. Record<string, {...}> describes zones with arbitrary names but the same shape.
Typing API Responses (Response Wrappers)
Finally, a common response format. The success field with the value true or false creates a discriminated union:
// Standard API response
interface ApiSuccessResponse<T> {
success: true;
data: T;
meta?: {
total: number;
page: number;
limit: number;
};
}
interface ApiErrorResponse {
success: false;
error: {
code: string;
message: string;
details?: Record<string, string>;
};
}
type ApiResponse<T> = ApiSuccessResponse<T> | ApiErrorResponse;
// Helper functions
function sendSuccess<T>(res: Response, data: T, meta?: ApiSuccessResponse<T>['meta']): void {
const response: ApiSuccessResponse<T> = { success: true, data };
if (meta) response.meta = meta;
res.json(response);
}
function sendError(res: Response, code: string, message: string, status: number = 400): void {
const response: ApiErrorResponse = {
success: false,
error: { code, message }
};
res.status(status).json(response);
}
// Usage in route
router.get('/zones/:zoneId/dinosaurs',
(req: Request<{ zoneId: string }, any, any, { page?: string; limit?: string }>, res: Response) => {
const zoneId = req.params.zoneId;
const page = parseInt(req.query.page || '1');
const limit = parseInt(req.query.limit || '20');
// Data simulation
const dinosaurs: Dinosaur[] = [];
sendSuccess(res, dinosaurs, { total: 0, page, limit });
}
);A client that checks if (response.success) has access to data in that branch and to error in the other one, because the compiler narrows the type based on a single field.
TypeScript with Node.js is a powerful combination: typed routes, middleware, configuration and API responses make the park backend as safe as a fence carrying 20,000 volts, and the compiler catches bugs before you start the server. My advice: validate environment variables at startup and client data at the entrance to the handler, because types disappear after compilation. In the editor below you will build a typed park API, and in the next lesson you will see how to extend other people's types with module augmentation.
Remember: types in the backend are the fence plan, and runtime validation is the current in the wires, so a safe park needs both.
Code for this lesson: index.ts
// TypeScript with Node.js - practical patterns
// Jurassic Park - Backend API
// 1. Typed interfaces for the API
interface Dinosaur {
id: string;
species: string;
diet: 'herbivore' | 'carnivore' | 'omnivore';
zone: string;
weight: number;
dangerLevel: 1 | 2 | 3 | 4 | 5;
}
interface ListDinosaursQuery {
zone?: string;
diet?: Dinosaur['diet'];
limit?: number;
offset?: number;
}
interface CreateDinosaurBody {
species: string;
diet: Dinosaur['diet'];
zone: string;
weight: number;
dangerLevel: Dinosaur['dangerLevel'];
}
// 2. Typing environment variables
interface EnvironmentVariables {
NODE_ENV: 'development' | 'production' | 'test';
PORT: string;
DATABASE_URL: string;
PARK_NAME: string;
MAX_VISITORS: string;
}
function validateEnv(required: string[]): Record<string, string> {
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
// In a real project: throw new Error(...)
console.log(`Note: missing variables: ${missing.join(', ')}`);
}
return process.env as Record<string, string>;
}
// 3. Typed configuration objects
interface DatabaseConfig {
host: string;
port: number;
name: string;
pool: { min: number; max: number };
}
interface ServerConfig {
port: number;
cors: {
origins: string[];
methods: ('GET' | 'POST' | 'PUT' | 'DELETE')[];
};
}
interface ParkZoneConfig {
name: string;
maxCapacity: number;
dangerLevel: number;
fenceVoltage: number;
}
interface AppConfig {
server: ServerConfig;
database: DatabaseConfig;
zones: Record<string, ParkZoneConfig>;
}
function loadConfig(): AppConfig {
return {
server: {
port: 4000,
cors: {
origins: ['http://localhost:3000'],
methods: ['GET', 'POST', 'PUT', 'DELETE']
}
},
database: {
host: 'localhost',
port: 27017,
name: 'jurassic_park',
pool: { min: 2, max: 10 }
},
zones: {
'zone-a': { name: 'Herbivore Valley', maxCapacity: 200, dangerLevel: 1, fenceVoltage: 5000 },
'zone-b': { name: 'Raptor Paddock', maxCapacity: 50, dangerLevel: 5, fenceVoltage: 15000 },
'zone-c': { name: 'T-Rex Kingdom', maxCapacity: 30, dangerLevel: 5, fenceVoltage: 20000 }
}
};
}
// 4. Typed API responses
interface ApiSuccess<T> {
success: true;
data: T;
meta?: { total: number; page: number; limit: number };
}
interface ApiError {
success: false;
error: { code: string; message: string };
}
type ApiResponse<T> = ApiSuccess<T> | ApiError;
function createSuccess<T>(data: T, meta?: ApiSuccess<T>['meta']): ApiSuccess<T> {
const response: ApiSuccess<T> = { success: true, data };
if (meta) response.meta = meta;
return response;
}
function createError(code: string, message: string): ApiError {
return { success: false, error: { code, message } };
}
// 5. Server simulation
const config = loadConfig();
const dinosaurs: Dinosaur[] = [
{ id: 'D001', species: 'T-Rex', diet: 'carnivore', zone: 'zone-c', weight: 7000, dangerLevel: 5 },
{ id: 'D002', species: 'Triceratops', diet: 'herbivore', zone: 'zone-a', weight: 6000, dangerLevel: 2 },
{ id: 'D003', species: 'Velociraptor', diet: 'carnivore', zone: 'zone-b', weight: 80, dangerLevel: 4 },
];
console.log(`=== ${config.database.name.toUpperCase()} API ===`);
console.log(`Server: port ${config.server.port}`);
console.log(`Database: ${config.database.host}:${config.database.port}/${config.database.name}`);
console.log(`Zones: ${Object.keys(config.zones).length}\n`);
// GET /dinosaurs simulation
console.log("GET /dinosaurs?zone=zone-b");
const query: ListDinosaursQuery = { zone: 'zone-b' };
const filtered = dinosaurs.filter(d => !query.zone || d.zone === query.zone);
const response1 = createSuccess(filtered, { total: filtered.length, page: 1, limit: 20 });
console.log(JSON.stringify(response1, null, 2));
// POST /dinosaurs simulation
console.log("\nPOST /dinosaurs");
const body: CreateDinosaurBody = {
species: 'Stegosaurus',
diet: 'herbivore',
zone: 'zone-a',
weight: 3500,
dangerLevel: 1
};
const newDino: Dinosaur = { id: 'D004', ...body };
const response2 = createSuccess(newDino);
console.log(JSON.stringify(response2, null, 2));
// GET /dinosaurs/unknown simulation
console.log("\nGET /dinosaurs/D999");
const notFound = createError('NOT_FOUND', 'Dinosaur with id D999 does not exist');
console.log(JSON.stringify(notFound, null, 2));
// Zone info
console.log("\n=== Park Zones ===");
for (const [id, zone] of Object.entries(config.zones)) {
console.log(`${id}: ${zone.name} (danger: ${zone.dangerLevel}, fence: ${zone.fenceVoltage}V)`);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. How do you type request parameters (params, body, query) in Express with TypeScript?
2. What type do process.env variables have by default in TypeScript?
Hands-on tasks in the game
- Code editor
Define server and database configuration interfaces, and a function that loads the configuration.
- Horizontal ordering
Arrange the elements of a typed Express route handler:
- Vertical ordering
Arrange the order of HTTP request processing in typed Express:
- Horizontal ordering
Arrange the elements of a mapped type in the correct order: