Skip to content

Quickstart

Getting started with @nhtio/tiny-typed-emitter is quick and easy. Just follow the steps below and you'll be up and running in no time.

Installation

You can install @nhtio/tiny-typed-emitter directly from your preferred package manager

sh
npm i @nhtio/tiny-typed-emitter
sh
pnpm add @nhtio/tiny-typed-emitter
sh
yarn add @nhtio/tiny-typed-emitter

Usage

You can use the TypedEventEmitter by importing it from the package.

TIP

Make sure that you also create an Event Map or Typescript will infer that there are no events that are subscribable or emittable.

typescript
import { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'
import type { EventMap } from '@nhtio/tiny-typed-emitter'

// Create a map of the types where the key is the name of the event
// and the value is a tuple representing the expected arguments
// for that event
type MyEventMap = EventMap<{
    foo: []
    bar: [string]
    baz: [any, ...any[]]
}>

// Create an instance of the TypedEventEmitter
const instance = new TypedEventEmitter<MyEventMap>()

You can also extend the TypedEventEmitter class:

typescript
import { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'
import type { EventMap } from '@nhtio/tiny-typed-emitter'

// Create a map of the types where the key is the name of the event
// and the value is a tuple representing the expected arguments
// for that event
type MyEventMap = EventMap<{
    foo: []
    bar: [string]
    baz: [any, ...any[]]
}>

// Extend the TypedEventEmitter class to already include the
// custom event map
class MyTypedEventEmitter extends TypedEventEmitter<MyEventMap> {}

// Create an instance of the extended TypedEventEmitter class
const instance = new MyTypedEventEmitter()