← Back to TypeScript Course | Chapter 28: Real World Projects | Lesson 2 of 14

Express + TypeScript के साथ REST API

Express को TypeScript के साथ combine करके typed HTTP APIs बनाई जा सकती हैं। Interfaces और request types route logic को predictable रखने में help करते हैं।
Syntax
typescript
import express, { Request, Response } from "express";

app.post("/path", (req: Request<Params, ResBody, ReqBody>, res: Response<ResBody>) => {
    // req.body is checked against ReqBody
});

Core Concept

Express और TypeScript के साथ एक REST API बनाने का मतलब है अपने route handlers के request और response objects को type करना, इसलिए req.body.email access करना एक declared shape के against checked होता है, silently any होने के बजाय।

उदाहरण: Core Concept

typescript
// import { Request, Response } from "express";
interface CreateUserBody { email: string; }
// app.post("/users", (req: Request<{}, {}, CreateUserBody>, res: Response) => {
//   console.log(req.body.email);
// });
console.log("req.body is checked against a declared shape, not any");

Basic Setup

एक basic setup express के साथ @types/express install करता है, और typed handlers Request<Params, ResBody, ReqBody> generics उपयोग करते हैं यह describe करने के लिए कि हर route पर exactly क्या expected है।

उदाहरण: Basic Setup

typescript
// npm install express
// npm install --save-dev @types/express
console.log("@types/express enables Request<Params, ResBody, ReqBody> generics");

Typed Example

एक typed example: app.post('/users', (req: Request<{}, {}, CreateUserBody>, res: Response<UserResponse>) => { ... }) ensure करता है कि handler का req.body CreateUserBody के against checked हो और इसके res.json(...) calls UserResponse के against checked हों।

उदाहरण: Typed Example

typescript
interface CreateUserBody { email: string; }
interface UserResponse { id: number; email: string; }
// app.post('/users', (req: Request<{}, {}, CreateUserBody>, res: Response<UserResponse>) => {
//   res.json({ id: 1, email: req.body.email });
// });
console.log("Both req.body and res.json() are checked against declared types");

Project Usage

एक असली project में, इन request/response interfaces को एक frontend client के साथ (एक shared-types package के ज़रिए) share करना API contract को दोनों ends पर enforced रखता है बिना किसी side के silently drift होने के।

उदाहरण: Project Usage

typescript
interface UserResponse { id: number; email: string; }
// Shared with a frontend client via a shared-types package.
const response: UserResponse = { id: 1, email: "[email protected]" };
console.log(response);

Best Practices

अपने compile-time types के साथ runtime validation जोड़ें (Zod या Joi जैसी एक library से), क्योंकि TypeScript के checks runtime पर गायब हो जाते हैं और एक untrusted client से एक malformed request body को रोक नहीं सकते।

उदाहरण: Best Practices

typescript
interface CreateUserBody { email: string; }
function isCreateUserBody(value: any): value is CreateUserBody {
  return typeof value?.email === "string";
}
// Runtime validation (e.g. Zod/Joi) catches what compile-time types can't.
console.log(isCreateUserBody({ email: "[email protected]" }));
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. Body को type किए बिना req.body.email पढ़ना, इसलिए यह any है और एक typo unnoticed रह जाता है।
  2. app.use(express.json()) भूल जाना, इसलिए req.body runtime पर undefined है भले ही यह type-check हो।
  3. Request<CreateUserBody> लिखना जब body third generic है, Request<{}, {}, CreateUserBody>।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.