Skip to content

Commit

Permalink
docs: add custom event types docs (#16609)
Browse files Browse the repository at this point in the history
Co-authored-by: 翠 / green <[email protected]>
  • Loading branch information
FreeJ1nG and sapphi-red authored May 7, 2024
1 parent 7a8ae49 commit 66f12ab
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
2 changes: 1 addition & 1 deletion docs/guide/api-hmr.md
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ Send custom events back to Vite's dev server.
If called before connected, the data will be buffered and sent once the connection is established.
See [Client-server Communication](/guide/api-plugin.html#client-server-communication) for more details.
See [Client-server Communication](/guide/api-plugin.html#client-server-communication) for more details, including a section on [Typing Custom Events](/guide/api-plugin.html#typescript-for-custom-events).
## Further Reading
Expand Down
30 changes: 27 additions & 3 deletions docs/guide/api-plugin.md
Original file line number Diff line number Diff line change
Expand Up @@ -625,16 +625,40 @@ export default defineConfig({

### TypeScript for Custom Events

It is possible to type custom events by extending the `CustomEventMap` interface:
Internally, vite infers the type of a payload from the `CustomEventMap` interface, it is possible to type custom events by extending the interface:

:::tip Note
Make sure to include the `.d.ts` extension when specifying TypeScript declaration files. Otherwise, Typescript may not know which file the module is trying to extend.
:::

```ts
// events.d.ts
import 'vite/types/customEvent'
import 'vite/types/customEvent.d.ts'
declare module 'vite/types/customEvent' {
declare module 'vite/types/customEvent.d.ts' {
interface CustomEventMap {
'custom:foo': { msg: string }
// 'event-key': payload
}
}
```

This interface extension is utilized by `InferCustomEventPayload<T>` to infer the payload type for event `T`. For more information on how this interface is utilized, refer to the [HMR API Documentation](./api-hmr#hmr-api).

```ts twoslash
import 'vite/client'
import type { InferCustomEventPayload } from 'vite/types/customEvent.d.ts'
declare module 'vite/types/customEvent.d.ts' {
interface CustomEventMap {
'custom:foo': { msg: string }
}
}
// ---cut---
type CustomFooPayload = InferCustomEventPayload<'custom:foo'>
import.meta.hot?.on('custom:foo', (payload) => {
// The type of payload will be { msg: string }
})
import.meta.hot?.on('unknown:event', (payload) => {
// The type of payload will be any
})
```

0 comments on commit 66f12ab

Please sign in to comment.