Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Context<Env> from middlewares are not inferred in factory.createHandlers #3467

Open
mecab opened this issue Sep 29, 2024 · 0 comments
Open
Labels

Comments

@mecab
Copy link

mecab commented Sep 29, 2024

What version of Hono are you using?

4.6.3

What runtime/platform is your app running on?

Node.js / Bun

What steps can reproduce the bug?

The Envs from middleware is inferred in the handlers which are created as app.get('/foo', middleware, ...), but it isn't when you create them using factory.createHandlers(middleware, ...).

Here's an example based on the doc:

import { Hono } from 'hono';
import { createFactory, createMiddleware } from 'hono/factory'
import { logger } from 'hono/logger'

const app = new Hono();
const factory = createFactory()

const middleware = createMiddleware<{ Variables: { foo: string } }>(async (c, next) => {
  c.set('foo', 'bar')
  await next()
})

const handlers = factory.createHandlers(logger(), middleware, async (c) => {
  // I suppose `c` is `Context<{ Variables: { foo: string } }, ...>`, but actually `Context<any, any, {}>`

  return c.json(c.get('foo'));
});

app
  .get('/api', ...handlers)
  .get('/api', logger(), middleware, async (c) => {
    // Here `c` is inferred as expected.
    return c.json(c.get('foo'));
  })

I attach how it looks in VSCode for reference
image

What is the expected behavior?

As I wrote in the code comment, the context type of c in createHandlers is inferred as Context<{ Variables: { foo: string } }, ...> so I can use c.get('foo') or c.var.foo with the inferred type, as like as it works for the handler which directly attached to app.

What do you see instead?

The type of c is Context<any, any, {}> so I cannot get benefit from the type. Although it works as expected for the directly attached handler.

Additional information

I am not 100% sure if my assumption that the inference works for the createHandlers. If it is not expected as design (or TypeScript constraint), sorry for my misunderstanding.

I have searched the issue and found #3202 (and its dups - #3341, #3198) is discussing the inference for middlewares, but I guess it is actually not relevant.

@mecab mecab added the triage label Sep 29, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant