Allow typing event context
See original GitHub issueQuestion: How to define context typescript type?
Hey, not sure if this is an h3 question or a lack of typecript knowledge from me.
I am using Nuxt 3 and am trying to add types to my server handlers. I have a simple server handle:
export default defineEventHandler((event) => { // event here is a H3Event object
const result = event.context.container.resolve()
return {
result
}
})
The event here is a H3Event:
interface H3Event {
'__is_event__': true;
event: H3Event;
req: IncomingMessage;
res: ServerResponse;
context: Record<string, any>;
}
And I have a middleware where I do the following:
export default defineEventHandler((event) => {
event.context.container = {
resolve: () => {
return 'ok'
}
}
})
I would like to “type” the event parameter, I would like my VSCode editor to be aware that the event parameter contains a context property that contains a resolve property that is a function that returns a string.
I tried extending the H3Event using the following:
declare module 'h3' {
interface H3Event {
context: Record<string, any> & {
resolve: () => string
};
}
}
But Typescript gives me the following error:
Subsequent property declarations must have the same type. Property ‘context’ must be of type Record<string, any>…
Is there a way to define the context type of the event parameter in a server middleware?
Issue Analytics
- State:
- Created a year ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
Thanks for the issue. I think we could introduce a new
EventContext
interface for easy extension. /cc @danielroe is this something you would like to work on?Related:
@ElMatella the problem with that is that all your middleware will have the context type of each middleware