---
url: https://node-ts.github.io/bus/api/bus-messages/functions/defineEvent.md
---
[API reference](../../index.md) / [@node-ts/bus-messages](../index.md) / defineEvent

# Function: defineEvent()

```ts
function defineEvent<TName>(name, options?): <TData>() => MessageDefinition<DefinedMessage<TName, TData>, TData>;
```

Defined in: [packages/bus-messages/src/define-event.ts:29](https://github.com/node-ts/bus/blob/2e6cf65c27833b707ae31ee623cfb6343770f434/packages/bus-messages/src/define-event.ts#L29)

Declares an event, something that happened that is published to every subscriber, without writing
a class. The definition creates events from their fields, and is used anywhere a message class is:
`handlerFor`, `startedBy` and `when`. The events it creates are plain objects, with `$name` and
`$version` added.

The name comes first and the fields second, so the name's literal type is inferred. Run
`bus generate-message-types` (in `@node-ts/bus-cli`) to have Dates, Maps, Sets, bigints and classes
in the fields restored when the event is received.

## Type Parameters

| Type Parameter |
| ------ |
| `TName` *extends* `string` |

## Parameters

| Parameter | Type | Description |
| ------ | ------ | ------ |
| `name` | `TName` | the `$name` of the event, which routes it, so make it unique |
| `options?` | [`DefineMessageOptions`](../interfaces/DefineMessageOptions.md) | the `$version` of the event's contract |

## Returns

a function that takes the type of the event's fields as its type argument, and returns
the definition

<`TData`>() => [`MessageDefinition`](../interfaces/MessageDefinition.md)<[`DefinedMessage`](../type-aliases/DefinedMessage.md)<`TName`, `TData`>, `TData`>

## Example

```ts
export const OrderPlaced = defineEvent('@my-org/orders/order-placed')<{
  orderId: string
  placedAt: Date
}>()
export type OrderPlaced = MessageOf<typeof OrderPlaced>

await bus.publish(OrderPlaced({ orderId: '1', placedAt: new Date() }))
handlerFor(OrderPlaced, async orderPlaced => orderPlaced.placedAt.getTime())
```
