title: Typesafe listeners using EventEmitter and Typescript in Node.js
body: <p>Given a <a href="https://www.typescriptlang.org/" rel="nofollow noreferrer">Typescript</a> interface and a class extending <a href="https://nodejs.org/" rel="nofollow noreferrer">Node.js</a> <a href="https://nodejs.org/api/events.html#events_class_eventemitter" rel="nofollow noreferrer">EventEmitter</a>, is it possible to define custom listeners that give typesafe check for the function arguments?</p>
  <p>Given the following example:</p>
  <pre class="lang-js prettyprint-override"><code>import { EventEmitter } from 'events';
  
  interface Payload {
      id: string;
      weight: number;
  }
  
  class CustomEventEmitter extends EventEmitter {
      constructor() {
          super();
  
          this.on('my_event', (data) =&gt; {
              // I would like data to be implicitly inferred as Payload type
              console.log(data.weight); // This should compile
              console.log(data.something); // This should not compile
          });
      }
  }
  </code></pre>
  <p>A node EventEmitter listener is defined as <code>(...args: any[]) =&gt; void)</code>, I would like to override the <code>any[]</code> type and use custom defined types instead. Is it possible?</p>