hono
hono copied to clipboard
Infer correct types when creating `MiddlewareHandler` dynamically
What is the feature you are proposing?
If you create a middleware from a function like a factory method, it can't infer types correctly in the handler:
const app = new Hono<{
Variables: {
foo: string
}
}>()
type CreateMiddleware = <E extends Env, P extends string>(
handler: (c: Context<E, P>) => any
) => MiddlewareHandler<E, P>
const createMiddleware: CreateMiddleware = () => {
return async () => {}
}
app.get('/abc/:id', async (c) => {
const foo = c.get('foo') // foo is string
const id = c.req.param('id') // id is inferred correctly.
type T = typeof id // string
})
app.get(
'/abc/:id',
createMiddleware(async (c) => {
const foo = c.get('foo') // foo is never
const id = c.req.param('id') // id is not inferred correctly.
type T = typeof id // string | undefined
})
)
This is a TypeScript limitation, but we have to find a way to resolve it.
Related to #3198