Skip to content

Event List

Vitaly Tomilov edited this page Aug 10, 2019 · 13 revisions

When working with a list of events, you may decide to access them by name. Modern TypeScript lets you do this, via keyof, while still controlling the event's name and type.

class Events {
    first = new SubEvent<number>();
    second = new SubEvent<string>();
    third = new SubEvent<boolean>();

    get<K extends keyof Events>(key: K) {
        return this[key];
    }
}

Then after creating a class object:

const events = new Events();

you can access each event via a string, with each name enforced to match an existing one, and each subscription being strongly-typed, based on the event's name:

events.get('first').subscribe((data: number) => {
    // data is strongly-typed
});

events.get('second').subscribe((data: string) => {
    // data is strongly-typed
});

events.get('third').subscribe((data: boolean) => {
    // data is strongly-typed
});
Clone this wiki locally