I'm trying to add strongly typed events to an EventEmitter-like system using TypeScript.
Currently, we define our types like:
interface TypedMsg<Name, T> {
messageType: Name;
message: T;
}
type TypedMsgFoo = TypedMsg<'FOO', string>;
type TypedMsgBar = TypedMsg<'BAR', number>;
type EitherFooOrBar = TypedMsgFoo | TypedMsgBar;
I would like to define an interface like:
interface EventHandler<T extends TypedMsg<any, any> {
on: (messageType: T.messageType, handler: (T.message) => void) => void;
}
But Typescript doesn't support extracting subtypes like T.messageType
. Is there another way to do this?
The end goal would be to define handlers with proper typing with just:
class FooBarHandler implements EventHandler<EitherFooOrBar> {
on(messageType: EitherFooOrBar.messageType) {...}
}