I’ve been working on implementing a validation middleware in Hono using Zod and @hono/zod-validator
. Here’s the code snippet of the middleware:
const validationMiddleware = (schema: ZodSchema, target: keyof ValidationTargets) => {
return createMiddleware(async (c, next) => {
await next()
zValidator(target, schema, (result, c) => {
if (!result.success) {
return c.json({
success: false,
error: {
code: 400,
message: result.error.issues[0].message,
innerError: {
timestamp: new Date(Date.now())
}
}
})
}
})
})
}
And I use it like this:
validationMiddleware(userValidation, 'json')
The issue I’m facing is that I can’t seem to get type safety on the return value. Specifically, when I try to use c.req.valid('json')
, TypeScript throws the following error:
TS2345: Argument of type string is not assignable to parameter of type never on the 'json' input
I’m puzzled about why TypeScript is inferring never instead of the expected type. Could someone please advise on how to resolve this and ensure type safety in this scenario? Thanks!