我正在用Typescript编写一个API,但尽管检查了if
,我还是得到了错误Property 'password' does not exist on type 'unknown'
。
第页。S.request.body
的类型是unknown
login: async (request: FastifyRequest, reply: FastifyReply) => {
if(!request.body){
reply.code(400).send({
message: "Missing request body"
})
return
}
const { username, password } = request.body
if(!username || !password){
reply.code(400).send({
message: "Missing username or password"
})
return
}
如何正确键入check?我已经可以捕捉到request.body === undefined
的情况,这是Typescript的问题吗?
请参阅有关如何在Fastify中指定主体类型(以及预期的查询参数等(的文档:https://www.fastify.io/docs/latest/TypeScript/#request
您需要将参数传递给FastifyRequest泛型类型,如下所示:
async (request: FastifyRequest<{
Body: {
username: string,
password: string
}
}>, reply: FastifyReply)