类型化路由
Hono 本身使用 TypeScript 编写。合理使用类型可以让路由参数、请求体和共享变量更清晰。
路由参数类型
c.req.param() 返回字符串。你需要自己处理数字转换和非法值:
app.get('/users/:id', (c) => {
const id = Number(c.req.param('id'))
if (!Number.isInteger(id) || id <= 0) {
return c.json({ message: 'Invalid user id' }, 400)
}
return c.json({ id })
})
不要把 Number() 转换藏在数据库查询里,否则错误会更晚暴露。
请求体类型
可以给 c.req.json() 标注类型:
type CreatePostInput = {
title: string
content: string
}
app.post('/posts', async (c) => {
const input = await c.req.json<CreatePostInput>()
return c.json({
id: crypto.randomUUID(),
title: input.title,
content: input.content,
})
})
这只是 TypeScript 编译期提示,不会自动验证运行时数据。公开 API 仍然应该使用验证器。
Variables 类型
中间件通过 c.set() 传递数据时,可以声明 Variables:
import { Hono } from 'hono'
type Variables = {
requestId: string
user: {
id: string
role: 'admin' | 'user'
}
}
const app = new Hono<{ Variables: Variables }>()
app.use(async (c, next) => {
c.set('requestId', crypto.randomUUID())
c.set('user', { id: 'u_1', role: 'admin' })
await next()
})
app.get('/me', (c) => {
const user = c.get('user')
return c.json(user)
})
这样 c.get('user') 会得到明确类型。
子路由类型
拆分路由时可以导出子应用:
// routes/posts.ts
import { Hono } from 'hono'
export const posts = new Hono()
.get('/', (c) => c.json([]))
.post('/', async (c) => {
const body = await c.req.json<{ title: string }>()
return c.json({ id: 1, title: body.title }, 201)
})
入口文件:
import { Hono } from 'hono'
import { posts } from './routes/posts'
const app = new Hono()
const routes = app.route('/posts', posts)
export type AppType = typeof routes
export default app
AppType 后续可以提供给 Hono Client,用于 RPC 类型推导。
类型与验证的边界
TypeScript 只能约束你写下的代码,不能保证客户端传来的 JSON 一定符合类型。建议把路由输入分成两层:
- TypeScript 类型:让编辑器和编译器帮助开发。
- 运行时验证:检查真实请求数据,返回可靠错误。
在 Hono 中,常见组合是 @hono/zod-validator 加 Zod schema。
相关内容
- Hono 是什么 介绍 Hono 的定位、核心特点、Web Standards 思路、多运行时能力,以及它与传统 Node.js Web 框架的差异。
- 安装和 Hello World 学习使用 create-hono 创建 Hono 项目,分别了解通用模板和 Node.js 模板的 Hello World 写法。
- 运行时选择 对比 Hono 在 Node.js、Cloudflare Workers、Bun、Deno 等运行时中的入口写法、部署方式和适用场景。
- 路由基础 学习 Hono 的 GET、POST、动态参数、通配符、路由分组和模块化路由写法。
- Context 详解 介绍 Hono Context 的 req、json、text、html、redirect、header、status、set、get 等常用 API。
- 中间件机制 学习 Hono 中间件的执行顺序、自定义中间件写法、路径匹配、next 调用和常见使用场景。