实战技巧
Node.js 中的 TypeScript
使用 ts-node、tsx 运行 TS、Express 类型化 API
Node.js 中的 TypeScript
在 Node.js 中运行 TypeScript 有多种方式,选对工具事半功倍。
学完本章你将: 使用 ts-node/tsx 运行 TS,类型化 Express API。
运行方式
bash
# 方式 1:ts-node(传统)
npm install -D ts-node
npx ts-node src/index.ts
# 方式 2:tsx(推荐,更快)
npm install -D tsx
npx tsx src/index.ts
# 方式 3:先编译再运行
npx tsc
node dist/index.js
Express + TypeScript
typescript
import express, { Request, Response, NextFunction } from "express";
const app = express();
// 类型化请求
interface User {
id: number;
name: string;
email: string;
}
app.get("/api/users/:id", (
req: Request<{ id: string }>,
res: Response<User | { error: string }>,
) => {
const id = req.params.id;
res.json({ id: 1, name: "Alice", email: "a@test.com" });
});
// 自定义中间件
function authMiddleware(
req: Request,
res: Response,
next: NextFunction
): void {
const token = req.headers.authorization;
if (!token) {
res.status(401).json({ error: "未授权" });
return;
}
next();
}
app.listen(3000, () => console.log("Server on :3000"));
类型化环境变量
typescript
// env.d.ts
declare namespace NodeJS {
interface ProcessEnv {
DATABASE_URL: string;
JWT_SECRET: string;
PORT?: string;
}
}
// 使用
const dbUrl = process.env.DATABASE_URL; // string(有类型!)
const port = parseInt(process.env.PORT || "3000");
文件操作
typescript
import fs from "fs/promises";
import path from "path";
async function readConfig(): Promise<Record<string, unknown>> {
const content = await fs.readFile(
path.join(__dirname, "config.json"),
"utf-8"
);
return JSON.parse(content) as Record<string, unknown>;
}