Skip to content

Commit

Permalink
fix(types): env variables override ContextVariableMap (#2987)
Browse files Browse the repository at this point in the history
* env variables should override ContextVariableMap

* add a test

---------

Co-authored-by: Yusuke Wada <[email protected]>
  • Loading branch information
KaelWD and yusukebe authored Jun 19, 2024
1 parent b9799e4 commit b074f07
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ export type Layout<T = Record<string, any>> = (props: T) => any
* @template E - Environment type.
*/
interface Get<E extends Env> {
<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]
<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]
<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]
}

/**
Expand All @@ -79,8 +79,8 @@ interface Get<E extends Env> {
* @template E - Environment type.
*/
interface Set<E extends Env> {
<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void
<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void
<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void
}

/**
Expand Down
20 changes: 18 additions & 2 deletions src/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1638,8 +1638,8 @@ declare module './context' {
}
}

describe('c.var with ContextVariableMap - test only types', () => {
it('Should no throw a type error', () => {
describe('ContextVariableMap type tests', () => {
it('Should not throw type errors with c.var', () => {
new Hono().get((c) => {
expectTypeOf(c.get('payload')).toEqualTypeOf<string>()
return c.json(0)
Expand All @@ -1649,6 +1649,22 @@ describe('c.var with ContextVariableMap - test only types', () => {
return c.json(0)
})
})

it('Should override ContextVariableMap with env variables', () => {
const middleware = createMiddleware<{
Variables: {
payload: number
}
}>(async (c, next) => {
c.set('payload', 123)
await next()
})

new Hono().get(middleware, (c) => {
expectTypeOf(c.get('payload')).toEqualTypeOf<number>()
return c.json(0)
})
})
})

/**
Expand Down

0 comments on commit b074f07

Please sign in to comment.