Search code examples
javascriptjsdoceventemitter

Is it possible to JSDoc a custom EventEmitter with the event's proper callback params?


I found a similar question here. However, even though it lists all the possible events, it doesn't include the callback params when I chose an event to listen to.

Here's a sample code

class BotClient extends EventEmitter {
    constructor() {
        super();
    };
    
    /**
     * @typedef {['ready' | 'messageCreate', ...any[]]} ClientEventsList
     */

    /**
     * @param {ClientEventsList} eventArg
     */
    addListener(...eventArg) {
        super.addListener(...eventArg);
    };
    /**
     * @param {ClientEventsList} eventArg
     */
    on(...eventArg) {
        super.on(...eventArg);
    };
};

Solution

  • Install the tiny-typed-emitter package. It doesn't add any overhead.

    Library adds no overhead. All it does is it simply reexports renamed EventEmitter with customized typings. You can check lib/index.js to see the exported code.

    And then declare BotClient in javascript with JSDocs as so:

    const { TypedEmitter } = require("tiny-typed-emitter");
    
    /**
     * @extends {TypedEmitter<{
         'ready': (value: boolean) => void
         'messageCreate': (message: string) => void
       }>}
     */
    class BotClient extends TypedEmitter {
      constructor() {
          super();
      };
    };
    

    This way both the event and the event's arguments are going to be typed.

    index.js

    Screenshot