如何使用TypeScript搭建服务器?

下面就来手把手教你怎么用 TypeScript 搭建一个后端服务器,我会以最常用的Express 框架为例,因为它是目前生态最完善、教程最多的方案,如果你接触过其他框架(Koa、Nest.js),思路也是类似的。

整个过程可以分为 5 步,半小时内就能跑起来你的第一个 TypeScript 服务器。

🚀 第一步:初始化项目

打开终端,新建一个文件夹并进入,然后初始化 Node.js 项目:

mkdir my-ts-server
cd my-ts-server
npm init -y

这会生成一个package.json 文件。

🛠️ 第二步:安装依赖

我们需要安装三部分内容:

1、Express(服务器框架本身)

2、TypeScript(开发依赖)

3、类型定义文件(让 TypeScript 知道 Express 里有什么函数、参数类型)

安装 Express
npm install express
安装 TypeScript 和 Node.js 的类型定义
npm install -D typescript @types/node @types/express

-D 表示开发依赖,因为typescript 只在开发阶段需要编译代码。

@types/express@types/node 是社区维护的类型声明,没有它们 TypeScript 会报红。

⚙️ 第三步:配置 TypeScript

在项目根目录创建一个tsconfig.json 文件,它是 TypeScript 的编译配置文件:

npx tsc --init

这会生成一个默认配置文件,我们把它简化一下,改成这样:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "outDir": "./dist",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

重点说明:

target: "ES2020":编译成较新版本的 JavaScript,支持 async/await。

module: "commonjs":Node.js 默认使用的模块系统。

outDir: "./dist":编译后的 JS 文件输出到dist 文件夹。

rootDir: "./src":你的 TypeScript 源码放在src 文件夹。

strict: true:开启严格模式,帮你写出更健壮的代码。

📝 第四步:编写服务器代码

在项目根目录创建src 文件夹,并在里面创建一个index.ts 文件:

mkdir src
touch src/index.ts

用任意编辑器打开src/index.ts,写入以下代码:

import express, { Request, Response } from 'express';
// 创建 Express 应用实例
const app = express();
const port = 3000;
// 定义一个简单的路由
app.get('/', (req: Request, res: Response) => {
  res.send('Hello, TypeScript + Express! 🚀');
});
// 启动服务器
app.listen(port, () => {
  console.log(Server is running at http://localhost:${port});
});

这里有一个新手容易困惑的点reqres 后面的: Request: Response 是 TypeScript 的类型注解,告诉编辑器这两个参数的类型,方便你写代码时看到自动补全。

▶️ 第五步:运行服务器

有两种运行方式:开发模式(自动重启)和生产模式(编译后运行)。

方式一:开发模式(推荐)

安装一个叫ts-node-dev 的工具,它能让你修改代码后自动重启服务器(类似 nodemon 但支持 TypeScript):

npm install -D ts-node-dev

然后在package.json"scripts" 字段里添加:

"scripts": {
  "dev": "ts-node-dev --respawn src/index.ts",
  "build": "tsc",
  "start": "node dist/index.js"
}

现在运行:

npm run dev

你会看到终端输出Server is running at http://localhost:3000,打开浏览器访问这个地址,就能看到Hello, TypeScript + Express! 🚀

方式二:生产模式

先编译 TypeScript 到 JavaScript:

npm run build

这会生成dist/index.js,然后运行:

npm start

🧠 一个更完整的示例:添加路由和 JSON 接口

上面的例子太简单了,我们写一个包含数据接口的示例,让你感受实际开发的样子。

修改src/index.ts

import express, { Request, Response } from 'express';
const app = express();
const port = 3000;
// 中间件:让 Express 能解析 JSON 请求体
app.use(express.json());
// 模拟数据库:一个用户列表
interface User {
  id: number;
  name: string;
  email: string;
}
let users: User[] = [
  { id: 1, name: 'Alice', email: 'alice@example.com' },
  { id: 2, name: 'Bob', email: 'bob@example.com' },
];
// 获取所有用户
app.get('/users', (req: Request, res: Response) => {
  res.json(users);
});
// 根据 ID 获取单个用户
app.get('/users/:id', (req: Request, res: Response) => {
  const id = parseInt(req.params.id, 10);
  const user = users.find(u => u.id === id);
  if (user) {
    res.json(user);
  } else {
    res.status(404).json({ message: 'User not found' });
  }
});
// 添加新用户
app.post('/users', (req: Request, res: Response) => {
  const newUser: User = {
    id: users.length + 1,
    name: req.body.name,
    email: req.body.email,
  };
  users.push(newUser);
  res.status(201).json(newUser);
});
app.listen(port, () => {
  console.log(Server running at http://localhost:${port});
});

关键点:

- 我们定义了一个interface User,这比纯 JS 多了一步,但好处是如果你写错了属性名(比如emial 而不是email),TypeScript 会立刻提示你。

req.paramsreq.body 现在都有了类型推断。

你可以用curl 或者 Postman 来测试:

获取所有用户
curl http://localhost:3000/users
添加用户
curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Charlie","email":"charlie@example.com"}'

🔧 常见问题与调试

Q:Cannot find module 'express' 错误?

A:确保你在正确的目录下运行了npm install,且node_modules 文件夹存在。

Q:运行ts-node-dev 时报错command not found

A:可能是因为全局没安装,用npx ts-node-dev ... 或者确保node_modules/.bin 在你的 PATH 里,直接用npm run dev 是最稳妥的。

Q:我想用更现代的框架(Nest.js、Fastify)?

A:思路完全一样,只是安装的包不同。

Nest.jsnpm install -g @nestjs/cli && nest new project-name

Fastifynpm install fastify @types/node,写法类似 Express 但性能更好。

1、初始化npm init,安装typescript +@types/xxx + 框架本体。

2、配置tsconfig.json 指定源码目录src 和输出目录dist

3、编码:在.ts 文件里写代码,利用接口(interface)和类型注解(type annotation)获得更好的开发体验。

4、运行:开发用ts-node-dev 实现热更新,生产用tsc 编译后用node 运行。

当你习惯了这套流程,用 TypeScript 写服务器不仅不会慢,反而因为类型提示和编译期错误检查,能省下不少排查 bug 的时间。

现在你可以动手试试了,如果遇到具体的报错信息,可以贴出来,我帮你看看。

文章摘自:https://idc.huochengrm.cn/fwq/25018.html

评论