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

fix(helper/adapter): correct env type #3885

Merged
merged 2 commits into from
Feb 4, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading