You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何泛型化重声明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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 10:40:35