Currently, I am in the process of developing an Engine
class that is capable of taking a map of various Module
classes upon its construction and instantiating them by passing itself. Subsequently, the created instances are then stored within the modules
. To ensure that the modules existing on the engine are known and can be declared expectedly by functions requiring an argument type of Engine
, I have utilized generics.
In addition, apart from holding these maps of module instances, this Engine
class possesses map event handlers as well. These handlers anticipate a callback that takes the Engine
instance as their first parameter. Registering these handlers can be accomplished through a public method available to the same class.
An illustrative example of a potential module structure may resemble the following:
class Renderer extends Module<{Renderer: Renderer}> {
constructor(engine: Engine<{Renderer: Renderer}>) {
super(engine);
this.engine.addEventHandler('draw', drawSomething);
}
renderText(message: string) {
console.log(message);
}
}
In this scenario, the event handler drawSomething
would appear similar to the one depicted below:
function drawSomething(engine: Engine<{Renderer: Renderer}>): void {
engine.modules.Renderer.renderText('hello world');
}
The issue I am currently facing pertains to the registration of the event handler drawSomething
. It appears that the generics initially passed are seemingly ignored during the verification process when ensuring that the handler is correctly typed. TypeScript has notified me with the following message:
Type 'Engine<{}>' is not assignable to type 'Engine<{ Renderer: Renderer; }>'
My primary objective at this point is to devise a method to make sure that TypeScript recognizes that when I register an event handler onto an instance of the Engine
containing specific modules, the handler will also be automatically passed that identical Engine
instance inclusive of those modules once it gets invoked.
I should mention that my current TypeScript version in use is 3.5.3.