在这个端点处理程序中,有没有办法限制req.query
在 NextJS 中NextApiRequest
只是string
类型而不是string | string[]
。例如,someQueryParam
这里是string | string[]
类型,但我想将其用作string
type
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<Response>
) {
const { someQueryParam } = req.query;
// pass in someQueryParam as a string into a function call
const result = functionCall(someQueryParam)
}
将 someQueryParam 传递到仅接受的函数时出现打字稿错误string
输入参数:
Argument of type 'string | string[]' is not assignable to parameter of type 'string'.
Type 'string[]' is not assignable to type 'string'.
作为参考,这里是定义NextApiRequest
在 Nextjs 库中
也欢迎任何以某种方式使用的建议someQueryParam
as string
键入而不是string | string[]
在将处理程序传递给函数之前先在处理程序中键入
最重要的问题是网址协议允许分配多个具有相同名称的查询名称。然后将它们作为string[]
而不是单个字符串。
E.g, ?value=one&value=two
。因此,如果仅使用一个字符串,则应由应用程序决定接受哪个值。
const value = Array.isArray(params.value) ? params.value[0] : params.value
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)