Related to the accepted answer: https://stackoverflow.com/a/63639280/17928771
EventEmitter3 is a generic class that takes an (as one example) Interface of Events/Handlers. I'm trying to restrict IRaceManager
emit
s to IRaceEvents
. I have tried:
Attempt 1.
class POSRaceManager implements IRaceManager extends EventEmitter<IRaceEvents> {}
let raceManager: IRaceManager = new POSRaceManager();
raceManager.emit('moo'); // error, no `emit` on IRaceManager
Attempt 2.
interface IRaceManager extends EventEmitter<IRaceEvents> {} // TS2749: 'EventEmitter' refers to a value, but is being used as a type here. Did you mean 'typeof EventEmitter'?
The following attempt works, but doesn't limit the emit
or on
to the IRaceEvents (or an extension of IRaceEvents)
Attempt 3.
This fails:
type RaceEventEmitterType<T extends IRaceEvents> = InstanceType<typeof EventEmitter>;
type IRaceManager<T extends IRaceEvents> = RaceEventEmitterType<T>;
let raceManager: IRaceManager = new POSRaceManager<IRaceEvents>;
raceManager.emit("moo"); // no error because of `InstanceType<typeof EventEmitter>`
Final attempt.
type RaceEventEmitterType<T extends IRaceEvents> = InstanceType<typeof EventEmitter<IRaceEvents>>; // Need to investigate what this does, actually. I overlooked a syntax error before.
Any ideas to restrict emissions from raceManager<?>
to T extends IRaceEvents
only?
Edit:
I am currently settled on the following (which works, I am just wondering if there is a way to resolve as above):
type RaceEventEmitter<T extends IRaceEvents> = InstanceType<typeof EventEmitter>;
type IRaceManager<T extends IRaceEvents> = RaceEventEmitter<T>;
class POSRaceManager extends EventEmitter<IRaceEvents> implements IRaceManager<IRaceEvents>;