Lesson 35 of 56 · Typescript
Express Server Typed with TypeScript
Duration: 25 minutes
Install dependencies
npm i express
npm i -D @types/express
Basic typed server
import express, { Request, Response } from 'express';
const app = express();
app.use(express.json());
app.get('/ping', (req: Request, res: Response) => {
res.json({ message: 'pong' });
});
app.post('/users', (req: Request<{ }, {}, { name: string }>, res: Response) => {
const { name } = req.body;
res.status(201).json({ id: Date.now(), name });
});
app.listen(4000, () => console.log('🚀 4000'));
Error‑handling middleware typed
import { NextFunction } from 'express';
function errorHandler(err: any, _req: Request, res: Response, _next: NextFunction) {
console.error(err);
res.status(500).json({ error: err.message ?? 'Internal Server Error' });
}
app.use(errorHandler);