-
Notifications
You must be signed in to change notification settings - Fork 2
Event List
Vitaly Tomilov edited this page Aug 10, 2019
·
13 revisions
When working with a long list of events, you may decide to access them by name. Modern TypeScript lets you do this, while still controlling the event type, with the help of keyof
, as shown in the example below.
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 the class:
const events = new Events();
you can access each event via a string, with strongly-typed subscription:
events.get('first').subscribe((data: number) => {
});
events.get('second').subscribe((data: string) => {
});
events.get('third').subscribe((data: boolean) => {
});