TypeScriptIntermediate
Node.js ও TypeScript
tsx/ts-node সেটআপ, process.env typing, Express + @types এবং async handler — সার্ভার-সাইড TS বাংলায়।
10টি অংশবাংলা ভাষায়
Node.js-এ TypeScript চলে — tsx দিয়ে সরাসরি run করা যায়, বা আগে compile করে। সার্ভার কোডে টাইপ দিলে API-র বাগ দ্রুত ধরা পড়ে।
Setup ও Run
# tsx ব্যবহারে সরাসরি TypeScript run
npm install -D typescript tsx @types/node
# package.json
"scripts": {
"dev": "tsx watch src/index.ts",
"build": "tsc",
"start": "node dist/index.js"
}process.env টাইপ
config.tstypescript
typescript
interface AppConfig {
port: number;
databaseUrl: string;
}
function readConfig(): AppConfig {
return {
port: Number(process.env.PORT ?? 3000),
databaseUrl: process.env.DATABASE_URL ?? "mongodb://localhost",
};
}
export const config = readConfig();Express + Types
import express from "express";
const app = express();
app.use(express.json());
interface Todo {
id: number;
title: string;
done: boolean;
}
const todos: Todo[] = [];
app.get("/todos", (_req: Request, res: Response<Todo[]>) => {
res.json(todos);
});
app.listen(3000, () => {
console.log("সার্ভার চলছে :3000");
});Async Error Handling
import type { Request, Response, NextFunction } from "express";
// async handler টাইপ
type AsyncHandler = (req: Request, res: Response, next: NextFunction) => Promise<void>;
const wrapAsync =
(handler: AsyncHandler) =>
async (req: Request, res: Response, next: NextFunction) => {
try {
await handler(req, res, next);
} catch (error) {
next(error);
}
};
app.get(
"/users",
wrapAsync(async (req, res) => {
const data = await getUsers();
res.json(data);
}),
);tsconfig for Node
ESM-প্রজেক্টে module: NodeNext আর CommonJS-এ module: commonjs — module system অনুযায়ী import syntax ঠিক হয়। @types/node ভুললে process/__dirname টাইপ পাওয়া যায় না।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।