Within my programming project, I have a foundational class called EventEmitter
, equipped with the on
method for attaching handlers to specific events:
class EventEmitter {
on(event: string, handler: Function) {
/* internally add new handler */
}
protected emit(event: string, ...args) {
/* trigger all event handlers listening on specified event */
}
}
Now, in my various subclasses, each may need to emit different events with unique arguments. I want a way to explicitly define which events should be emitted by a particular subclass:
class MyClass extends EventEmitter {
on(event: 'event1', handler: (arg1: number) => void): void;
on(event: 'event2', handler: (arg1: string, arg2: number) => void): void;
}
However, when trying to implement this approach, TypeScript (tsc 1.8) raises errors:
error TS2415: Class 'MyClass' incorrectly extends base class 'EventEmitter'.
Types of property 'on' are incompatible.
Type '(event: "event1", handler: (arg1: number) => void) => void' is not assignable to type '(event: string, handler: Function) => void'.
Type '(event: "event1", handler: (arg1: number) => void) => void' does not match the signature '(event: string, handler: Function): void'
error TS2382: Specialized overload signature is not compatible with non-specialized signature.
error TS2391: Missing function implementation following declaration.
Therefore, I am searching for an alternative method to specify the events that my subclass can emit.
EDIT: After researching, I stumbled upon the term Specialized Signatures, but it appears to be designed for interfaces only, not suitable for implementing in new TypeScript code.
Further exploration led me to a related question from 2015 in another forum thread. However, the suggested solution offered there seemed inadequate. Are there any other contemporary approaches to handle this issue effectively in TypeScript?