0
0
mirror of https://github.com/honojs/hono.git synced 2024-11-21 18:18:57 +01:00

fix(types): use ContextVariableMap in Context<any> (#3134)

* fix(types): use `ContextVariableMap` in `Context<any>`

* use `any`
This commit is contained in:
Yusuke Wada 2024-07-16 21:57:33 +09:00 committed by GitHub
parent 1afecac402
commit 024ec0ff8d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 25 additions and 4 deletions

View File

@ -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)
}
@ -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
}

View File

@ -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'
@ -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))
})
})
/**