I am just wondering if in TypeScript you can define custom events on your classes or interfaces?
What would this look like?
Here's a simple example of adding custom-type events to your class, using sub-events:
class MyClass {
readonly onMessage: SubEvent = new SubEvent();
readonly onData: SubEvent = new SubEvent();
sendMessage(msg: string) {
this.onMessage.emit(msg);
}
sendData(data: MyCustomType) {
this.onData.emit(data);
}
}
And then any client can subscribe to receive those events:
const a = new MyClass();
const sub1 = a.onMessage.subscribe(msg => {
// msg here is strongly-typed
});
const sub2 = a.onData.subscribe(data => {
// data here is strongly-typed
});
And when you no longer need the events, you can cancel the subscriptions:
sub1.cancel();
sub2.cancel();