Skip to content

Commit

Permalink
fix(helper/adapter): correct env type (#3885)
Browse files Browse the repository at this point in the history
* fix(helper/adapter): correct `env` type

* support another pattern and add test
  • Loading branch information
yusukebe authored Feb 4, 2025
1 parent 65edaf2 commit 0847a08
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 12 deletions.
38 changes: 32 additions & 6 deletions src/helper/adapter/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,39 @@ describe('env', () => {
MY_VAR: string
}
}
const app = new Hono<Env>()

it('Should set the type of the Context correctly and not throw a type error')
app.get('/var', (c) => {
const { MY_VAR } = env<{ MY_VAR: string }>(c)
return c.json({
var: MY_VAR,
it('Should not throw type errors with env has generics', () => {
const app = new Hono()
app.get('/var', (c) => {
const { MY_VAR } = env<{ MY_VAR: string }>(c)
expectTypeOf<string>(MY_VAR)
return c.json({
var: MY_VAR,
})
})
})

it('Should not throw type errors with Hono has generics', () => {
const app = new Hono<Env>()

app.get('/var', (c) => {
const { MY_VAR } = env(c)
expectTypeOf<string>(MY_VAR)
return c.json({
var: MY_VAR,
})
})
})

it('Should not throw type errors with env and Hono have generics', () => {
const app = new Hono<Env>()

app.get('/var', (c) => {
const { MY_VAR } = env<{ MY_VAR: string }>(c)
expectTypeOf<string>(MY_VAR)
return c.json({
var: MY_VAR,
})
})
})
})
Expand Down
10 changes: 4 additions & 6 deletions src/helper/adapter/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,11 @@ export type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-lig

export const env = <
T extends Record<string, unknown>,
C extends Context = Context<
{} & {
Bindings: T
}
>
C extends Context = Context<{
Bindings: T
}>
>(
c: C,
c: T extends Record<string, unknown> ? Context : C,
runtime?: Runtime
): T & C['env'] => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down

0 comments on commit 0847a08

Please sign in to comment.