TypeScript报错NextApiRequest不可赋值给Request类型该如何修复
报错原因
NextApiRequest 定义的 url 属性为可选类型 string | undefined,但 graphqlHTTP 要求传入的请求对象的 url 必须为非空 string,因此触发类型不兼容报错。你运行时没有问题说明实际场景下 req.url 始终存在,仅需解决类型层面的不匹配即可。
修复方案
方案1:快速类型断言
确认运行时 req.url 一定存在的场景下,可以直接通过类型断言跳过TS检查。由于NextApiRequest和graphqlHTTP要求的Request类型没有直接继承关系,需要先断言为unknown再转目标类型:
const handler = async (req: NextApiRequest, res: NextApiResponse) => { await graphqlHTTP({ graphiql: true, rootValue, schema })(req as unknown as Request, res) }
方案2:运行时兜底(更稳妥)
给req.url补充默认值,既解决类型问题,也能覆盖极端场景下url为undefined的异常情况:
const handler = async (req: NextApiRequest, res: NextApiResponse) => { req.url = req.url ?? '/' await graphqlHTTP({ graphiql: true, rootValue, schema })(req, res) }
内容的提问来源于stack exchange,提问作者user15453461
相关产品推荐
相关产品推荐

