Learn
← Previous Next →

Hari 23: TypeScript di Node.js & Express

55 min Last updated 09 Apr 2026

Type-safe Express Routes (Simulasi)

// Type untuk request/response Express
interface Request

{ params: P; query: Q; body: B; } interface Response { json: (data: unknown) => void; status: (code: number) => Response; send: (data: string) => void; } // Route handler type type Handler

= (req: Request, res: Response) => void | Promise; // Type-safe route definitions type UserParams = { id: string }; type UserQuery = { include?: "posts" | "profile" }; type CreateUserBody = { nama: string; email: string; password: string }; const getUser: Handler = (req, res) => { const { id } = req.params; // string const include = req.query.include; // "posts" | "profile" | undefined res.json({ id, include }); };


💡 Notice: Map<string, Handler> sebagai router sangat efisien (O(1) lookup). Pattern ini mirip dengan implementasi internal Express.js.

Assignment

Buat type-safe router sederhana. Router menyimpan handlers per method+path, dan bisa dipanggil untuk simulate request.

Expected output:

GET /users: [{"id":1,"nama":"Budi"}]
POST /users: {"id":2,"nama":"Sari","email":"s@s.com"}
GET /users/:id: {"id":"1","nama":"Budi"}
TS index.ts
Solution
Output