TypeScript + Node.js 实战
Node.js 本身不识别 TS,需要借助 ts-node/tsx 直接运行,或先编译成 JS 再运行。本节从环境搭建到写一个可运行的 HTTP 服务,走完 TS 后端的最小闭环。
环境准备
初始化项目并安装依赖:
npm init -y
npm i -D typescript ts-node @types/node
npx tsc --init
@types/node 提供 fs、http、process 等内置模块的类型。tsconfig 至少开启 strict:
{
"compilerOptions": {
"target": "ES2022",
"module": "commonjs",
"strict": true,
"outDir": "dist",
"sourceMap": true
}
}
sourceMap 让运行时报错能映射回 .ts 源码的行号。
第一个脚本:读取文件
先体验"写 TS 跑 Node":
import * as fs from "node:fs";
import * as path from "node:path";
function readFirstLine(file: string): string | null {
const text = fs.readFileSync(file, "utf-8");
return text.split("\n")[0] ?? null;
}
console.log(readFirstLine(path.join(__dirname, "package.json"))); // 输出:{
用 ts-node 直接运行
开发期不必每次编译,直接执行并监听改动:
npx ts-node src/index.ts # 运行一次
npx ts-node-dev src/index.ts # 监听文件,改动自动重启
用 TypeScript 写 HTTP 服务
用内置 http 模块写一个返回 JSON 的服务,接口类型清晰可见:
import * as http from "node:http";
interface Message {
message: string;
time: string;
}
const server = http.createServer((req, res) => {
const body: Message = {
message: "Hello TypeScript",
time: new Date().toISOString(),
};
res.writeHead(200, { "Content-Type": "application/json; charset=utf-8" });
res.end(JSON.stringify(body));
});
server.listen(3000, () => {
console.log("服务已启动: http://localhost:3000"); // 输出:服务已启动: ...
});
访问 http://localhost:3000 即可看到 JSON 响应。
环境变量的类型安全
process.env 值的类型是 string | undefined,读取时用类型收窄更安全:
function getPort(): number {
return Number(process.env.PORT ?? 3000); // ?? 兜底默认值
}
const token: string | undefined = process.env.API_TOKEN;
if (token) console.log(token.toUpperCase()); // 收窄后可安全调用方法
console.log("端口:", getPort()); // 输出:端口: 3000
小结
TS + Node 实战要点:ts-node 跑开发、tsc 出产物、@types/node 提供 API 类型,接口与类型收窄守护环境变量与网络数据,重构更安全。