如何泛型化重声明NextApiRequest接口以指定body类型?
如何为NextApiRequest的body定义泛型类型
正确的类型重声明方式
在项目根目录的next.d.ts文件中,通过模块扩展重新定义带泛型的NextApiRequest接口,直接覆盖body属性的类型:
declare module 'next' { // 给泛型参数设置默认值any,兼容原有未指定类型的场景 interface NextApiRequest<T = any> { body: T // 你的测试属性foot可以在这里继续定义 foot?: boolean } }
为什么之前的写法不生效
你之前的继承式扩展(extends NextApiRequest)会触发TypeScript的接口合并规则:原接口的body: any和新定义的body: T会交叉成any(因为any与任何类型交叉结果都是any),所以req.body依然显示为any类型,而新增的foot属性不受影响。
在API路由中使用
在/pages/api/hello.ts里指定泛型参数后,body的类型就能正确识别:
import type { NextApiRequest, NextApiResponse } from 'next' export default function handler( req: NextApiRequest<{ username: string; age: number }>, res: NextApiResponse ) { // req.body 现在是 { username: string; age: number } 类型,不再是any const { username, age } = req.body res.status(200).json({ message: `Hello ${username}, you are ${age} years old` }) }
额外说明
- 如果需要支持
body为undefined的场景,可以把泛型的默认值改为T = any | undefined,或者直接定义body: T | undefined - 模块扩展会自动保留原
NextApiRequest的所有属性(比如query、method等),不需要手动继承
内容的提问来源于stack exchange,提问作者kyun
相关产品推荐
相关产品推荐

