Reputation: 1481
I am writing an API in Typescript, but I got the error Property 'password' does not exist on type 'unknown'
despite the if
check.
P.S. the type for request.body
is 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
}
How can I type check this correctly? I can already catch the case where request.body === undefined
, is this an issue of Typescript?
Upvotes: 1
Views: 94
Reputation: 2458
See the documentation on how to specify the body type (and the expected query parameters, and so on) in Fastify: https://www.fastify.io/docs/latest/TypeScript/#request
You'll need to pass parameters to the FastifyRequest generic type, like so:
async (request: FastifyRequest<{
Body: {
username: string,
password: string
}
}>, reply: FastifyReply)
Upvotes: 3