我正在尝试按照下面的Fastify和Typescript文档构建一个简单的端点:
https://www.fastify.io/docs/v3.1.x/TypeScript/
export default async function foo(fastify: any) {
const MyInstance = new Foo(fastify.db);
app.get<{ Querystring: IQueryString, Headers: IHeaders }>(
"/foo",
async (request: FastifyRequest, reply: FastifyReply) => {
console.log(request.query); // *prints query object*
const { queryObj } = request.query; // *Gives error: Object is of type 'unknown'*
const result = await MyInstance.getFoo(queryObj);
reply.status(200).send(result);
}
);
}当我尝试访问request.query对象时,为什么会出现该错误?我该如何修复它?
发布于 2021-07-08 22:26:33
默认情况下,FastifyRequest.query的类型RequestQuerystringDefault映射到unknown,因为您无法猜测您想要为它设置哪些属性/类型。
如果您为某些请求的query定义了类型,只需定义该request type并使用它:
type MyRequest = FastifyRequest<{
Querystring: { queryObj: MyQueryObject }
}>然后将其指定为预期的请求类型:
async (request: MyRequest, reply: FastifyReply) => {
const { queryObj } = request.query // Ok
}https://stackoverflow.com/questions/67288886
复制相似问题