Skip to content

kimamula/ts-eventemitter

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

DEPRECATED

As of TypeScript 2.1, you can easily define a type safe EventEmitter with keyof and therefore you don't need this package anymore. See https://github.com/kimamula/TypeScript-definition-of-EventEmitter-with-keyof.

ts-eventemitter

A thin TypeScript wrapper for EventEmitter which provides with type-safety.

Install

npm install ts-eventemitter

Usage

  • Define your EventEmitter.
import TsEventEmitter from 'ts-eventemitter';

export interface MyEventEmitter extends TsEventEmitter {
    event(name: 'foo'): TsEventEmitter.Event0<this>;
    event(name: 'bar'): TsEventEmitter.Event1<this, string>;
    event(name: 'baz'): TsEventEmitter.Event1<this, { id: number; name: string; }>;
    event(name: string): TsEventEmitter.Event;
}

const MyEventEmitter: MyEventEmitter = TsEventEmitter.create();

export default MyEventEmitter;
  • Use it.
import MyEventEmitter from 'MyEventEmitter';

MyEventEmitter.event('foo').on(() =>
    console.log('foo')
).event('bar').on(name =>
    console.log(`Hello, ${name}`)
).event('baz').on(({id, name}) =>
    console.log(`Hello, ${name}. Your id is ${id}`)
);

MyEventEmitter.event('foo').emit();
MyEventEmitter.event('bar').emit('kimamula');
MyEventEmitter.event('baz').emit({id: 1, name: 'kimamula'});

// The below codes raise compilation errors
MyEventEmitter.event('fo').emit(); // typo
MyEventEmitter.event('bar').on((id: number) => {}); // wrong argument type
MyEventEmitter.event('baz').emit(1); // wrong argument type

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published