Skip to content

Allow typing event context #122

@ElMatella

Description

@ElMatella

Question: 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?

Metadata

Metadata

Assignees

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions