Skip to content

Commit

Permalink
fix(types): use ContextVariableMap in Context<any> (#3134)
Browse files Browse the repository at this point in the history
* fix(types): use `ContextVariableMap` in `Context<any>`

* use `any`
  • Loading branch information
yusukebe committed Jul 16, 2024
1 parent 1afecac commit 024ec0f
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 4 deletions.
19 changes: 16 additions & 3 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -519,9 +519,15 @@ export class Context<
* await next()
* })
* ```
```
*/
set: Set<E> = (key: unknown, value: unknown) => {
set: Set<
IsAny<E> extends true
? {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Variables: ContextVariableMap & Record<string, any>
}
: E
> = (key: string, value: unknown) => {
this.#var ??= new Map()
this.#var.set(key, value)
}
Expand All @@ -539,7 +545,14 @@ export class Context<
* })
* ```
*/
get: Get<E> = (key: unknown) => {
get: Get<
IsAny<E> extends true
? {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Variables: ContextVariableMap & Record<string, any>
}
: E
> = (key: string) => {
return this.#var ? this.#var.get(key) : undefined
}

Expand Down
10 changes: 9 additions & 1 deletion src/types.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* eslint-disable @typescript-eslint/ban-types */
/* eslint-disable @typescript-eslint/no-unused-vars */
import { expectTypeOf } from 'vitest'
import type { Context } from './context'
import { Context } from './context'
import { createMiddleware } from './helper/factory'
import { Hono } from './hono'
import { poweredBy } from './middleware/powered-by'
Expand Down Expand Up @@ -1748,6 +1748,14 @@ describe('ContextVariableMap type tests', () => {
return c.json(0)
})
})

it('Should use ContextVariableMap when c is Context<any>', () => {
const c = new Context(new Request('http://localhost'))
expectTypeOf(c.get('payload')).toEqualTypeOf<string>()
expectTypeOf(c.var.payload).toEqualTypeOf<string>()
// @ts-expect-error the value of payload should be string
expectTypeOf(c.set('payload', 123))
})
})

/**
Expand Down

0 comments on commit 024ec0f

Please sign in to comment.