Socket
Socket
Sign inDemoInstall

tiny-typed-emitter

Package Overview
Dependencies
0
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    tiny-typed-emitter

Fully type-checked EventEmitter


Version published
Weekly downloads
257K
increased by18.92%
Maintainers
1
Install size
6.22 kB
Created
Weekly downloads
 

Readme

Source

tiny-typed-emitter

Have your events and their listeners type-checked with no overhead.

npm version

Install

Simply add the dependency using npm:

$ npm i tiny-typed-emitter

or using yarn:

$ yarn add tiny-typed-emitter

Usage

  1. import tiny-typed-emitter library:
import { TypedEmitter } from 'tiny-typed-emitter';
  1. define events and their listener signatures (note: quotes around event names are not mandatory):
interface MyClassEvents {
  'added': (el: string, wasNew: boolean) => void;
  'deleted': (deletedCount: number) => void;
}
  1. on this step depending on your use case, you can:
  • define your custom class extending EventEmitter:
    class MyClass extends TypedEmitter<MyClassEvents> {
      constructor() {
        super();
      }
    }
    
  • create new event emitter instance:
    const emitter = new TypedEmitter<MyClassEvent>();
    

Generic events interface

To use with generic events interface:

interface MyClassEvents<T> {
  'added': (el: T, wasNew: boolean) => void;
}

class MyClass<T> extends TypedEmitter<MyClassEvents<T>> {

}

Compatible subclasses with different events

The type of eventNames() is a superset of the actual event names to make subclasses of a TypedEmitter that introduce different events type compatible. For example the following is possible:

class Animal<E extends ListenerSignature<E>=ListenerSignature<unknown>> extends TypedEmitter<{spawn: () => void} & E> {
  constructor() {
    super();
  }
}

class Frog<E extends ListenerSignature<E>> extends Animal<{jump: () => void} & E> {
}

class Bird<E extends ListenerSignature<E>> extends Animal<{fly: () => void} & E> {
}

const animals: Animal[] = [new Frog(), new Bird()];

No Overhead

Library adds no overhead. All it does is it simply reexports renamed EventEmitter with customized typings. You can check lib/index.js to see the exported code.

Keywords

FAQs

Last updated on 24 Jul 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc